简体   繁体   中英

Trying to upload using ajax (Not working)

I am trying to upload a file and some text with it using ajax, but my problem is that it's not uploading to the database. I tried to use console.log to fix the problem but all it does is redirect me to the home page of my website, so it means there's an error. Am I doing something wrong? Please help me.

Javascript:

    <script>
  $(document).ready(function() {
    $("#post-btn").click(function(e) {
      var fd = new FormData();
      var pst = ("#txt").value;
      var files = document.getElementById("fileToUpload").files[0];

      e.preventDefault();
      // Check if file selected or not
    if(('#fileToUpload').length != 0 ){
       fd.append('fileToUpload',files[0]);

       $.ajax({
          url: 'posting.php',
          type: 'post',
          data: {pst: txt, fileToUpload: fd},
          contentType: false,
          processData: false,
          complete: function(r){
             if(r != 0){
                console.log(r.responseText);
             }else{
                alert('file not uploaded');
             }
          },
       });
    }else{
       alert("Select a file!");
    }

    });
  });
</script>

posting.php:

<?php 
$thePst = $_POST['txt'];
if (strpos($thePst, '<script>') !== false) {     echo "<script>history.go(-1)</script>";
  exit();
} else {

session_start();


if (isset($_POST['txt'])) {

?>

<?php

    $sender = $_SESSION['username'];
    $post1 = $_POST['txt'];
    $post = nl2br($post1);
    $submit = $_POST['submit'];
    $host = "localhost";
    $user = "root";
    $pass = "";
    $dbName = "posts";
    $id = $_SESSION['id'];
    $img = $_SESSION['img'];
    $stringLength = strlen($post);

    if (isset($post) && $stringLength <= 550 && strpos($post, '<script>') !== true) {
      $target_dir = "attatch/";
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
      $uploadOk = 1;
      $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));


        if (file_exists($target_file)) {
          echo "Sorry, file already exists.";
          $uploadOk = 0;
        }

        if ($_FILES["fileToUpload"]["size"] > 30000) {
          $uploadOk = 0;
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" && $imageFileType != "tiff" && $imageFileType != "mp4" && $imageFileType != "mov" && $imageFileType != "mkv") {
          echo "Sorry, only JPG, JPEG, PNG, TIFF & GIF files are allowed.";
          $uploadOk = 0;
        }

        if ($uploadOk == 0) {
          echo "Sorry, your file was not uploaded.";
        } else {
          $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
          $random = substr(str_shuffle($permitted_chars), 0, 25);
          $newfilename = $sender.".".$random.".".$imageFileType;
          if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "attatch/" . $newfilename)) {
            
          } else {
            echo "Sorry, there was an error uploading your file.";
          }
        }

        $today = date("F j, Y, g:i a");

      try {
        $attach = 'attatch/'.$newfilename;
        $conn = new PDO("mysql:host=$host;dbname=$dbName", $user, $pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        

        $preparedStatement = $conn->prepare('INSERT INTO posts (sender, post, sender_id, image_attach, sender_img, date) VALUES (:sender, :post, :sender_id, :image_attach, :sender_img, :tod)');

        $preparedStatement->bindParam(':sender', $sender);
        $preparedStatement->bindParam(':post', $post);
        $preparedStatement->bindParam(':sender_id', $id);
        $preparedStatement->bindParam(':image_attach', $attach);
        $preparedStatement->bindParam(':sender_img', $img);
        $preparedStatement->bindParam(':tod', $today);
        $preparedStatement->execute();
    } catch(PDOException $e) {
      echo "Error: " . $e->getMessage();
  } finally {
    $sess = $_SESSION['id'];
    echo "<script>history.go(-1)</script>";
  }
  $conn = null;
} else {
  echo "<script>history.go(-1)</script>";
}
?>

<?php 
}else{
     header("Location: index");
     exit();
}
 ?>
<?php } ?> 

Your help is appreciated.

You need to:

  • Include all the data you want in the FormData object
  • Pass the FormData object to data: directly without wrapping it in another object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM