-3

I am working with an ajax PHP upload, the upload works well without ajax jQuery. I went to Google to find more resources on it and adjusted my code several times but still get the same error at the backend that file is empty. This is my code.

At the frontend


<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>

My jQuery code

$(function(){
     $("#chatsCard").on('click', '#sendImg', function (e){
     e.preventDefault();
     //alert("test");
    var filedata = $("#file").prop("files")[0];
    var recipient = $("#uname").html();

//alert(filedata);

$.ajax({
      type:'post',
      url:'upload.php',
      contentType:false,
      processData:false,
      cache:false,
      dataType:'json',
data:{
       //rec:recipient,
       filedata
           },
success:function(data){
         alert (data);

}
});//ajax end
});//click end
});//doc end

Backend

<?php
   session_start();
   require("assets/db.php");
   $logged = $_SESSION['logged'];

//This is always my ajax response.
if(empty($_FILES['file'])){
    $response = "No picture selected";
    echo json_encode($response);
exit;
}

    $imgFolder = "media/";
    $fileTpath = $_FILES['file']['tmp_name']; 
    $fileSize = filesize($fileTpath);
    $info = finfo_open(FILEINFO_MIME_TYPE);
    $filetype = finfo_file($info, $fileTpath);
    $filetype = explode ("/",$filetype);
    $filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");

//rename image.
    $newName = uniqid(8);
    $newName = "recipient". 
    $newName. "."  . $filetype;

//check file size
if($fileSize > 21464568){
    $response = "Picture is greater than 2MB, Resize and try again";
    echo json_encode($response);
exit;
}

//check format.
elseif(!in_array($filetype, $allowedFiles)){
    $response= "You are only allowed to upload jpeg,jpg or png";
    echo json_encode($response);
exit;
}

//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
    $response = "Failed!!! Upload again!!!";
    echo json_encode($response);
exit;
}

//move to folder.
else{
  move_uploaded_file($fileTpath,$imgFolder .$newName);
    $recipient = $_POST['rec'];
    $time = date("d-M-y")." at ". date("h:ia");
    $msg = "media";

//insert to messaging
    $q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
    $stm = $conn->prepare ($q);
    $stm->bind_param("ssss",$msg,$logged,$recipient,$time);
    $stm->execute();

//insert media details

    $q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
    $stm = $conn->prepare ($q1);
    $stm->bind_param("sss",$logged,$newName,$fileType);
    $stm->execute();

//json response
    $response = "success";
    echo json_encode($response);
exit;
}

?>

Since I removed the jQuery and the uploading works normally, I assumed the problem is not from the backend so I focused on the jQuery by tweaking it to these

//First change
    var fd = new FormData();
    var file = $("#file").props('files')[0];
    var file data= fd.append("file",filedata);

//This still gives no picture selected.


//Second change
var fd = new FormData($("#mediaPic")[0])

//Passed fd as data but still the same response.

//Tried other stuffs I got on Google to get the image data but still d same response.
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mayor Abel
  • 15
  • 3
  • 1
    Does this answer your question? [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – code Sep 26 '21 at 05:44
  • Have you checked your browser's console for error messages. You have a number of *blaring* syntax errors in the code you've provided. – freedomn-m Sep 26 '21 at 07:02
  • "*still get the same error*" - do you get an error? What is it? Or is it just that your file in php is blank/empty? – freedomn-m Sep 26 '21 at 07:02

1 Answers1

1

You just need to post FormData() object, Append method returns null. Datatype text is preferred. So the final jQuery code would be:

$(function(){
    $("#sendImg").on('click', function (e){
        e.preventDefault();
        //alert("test");
        var recipient = $("#uname").html();
        
        var form_data   = new FormData();
        var file = $("#file").prop('files')[0];

        form_data.append('file', file);
            
        $.ajax({
            url: 'upload.php',
            dataType: 'text',
            type: 'post',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            success: function(data) {
                alert(data);
            }
        });//ajax end
    });//click end
});//doc end

To add additional value with form_data, simple use before submitting

form_data.append("rec", "value");