1

For some reason, when I don't use Ajax, the image file in the form being processed comes through just fine, but not when using the Ajax script below.

Can't figure out why...

Note: Not all form fields are image files (there are some text fields).

jQuery.ajax({
    method: 'POST',
    url: 'actions/listings-add.php',
    data: $('#form').serialize(),
    dataType:'json',
    success: function(msg){
        if(parseInt(msg.status)==1)
        {
            window.location=msg.txt;
        }
        else if(parseInt(msg.status)==0)
        {
            error(1,msg.txt);
        }
    }
});
Zain Aftab
  • 703
  • 7
  • 21
AEP
  • 11
  • 2
  • That's because dataType json does not support image objects. – JkAlombro Jul 22 '19 at 05:03
  • @JkAlombro That makes sense. What dataType would support image objects? – AEP Jul 22 '19 at 05:05
  • use these with ajax `type : "POST", data : new FormData(formid), cache : false, contentType : false, processData : false,` – Devsi Odedra Jul 22 '19 at 05:07
  • @DevsiOdedra is right. For more details about it you can check it here https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – JkAlombro Jul 22 '19 at 05:13

1 Answers1

0

JSON does not work with "file" inputs, because they need to be transfered with multipart/form-data. To upload files using AJAX, you can either use FormData to also transfer the file input or if you have a normal rest api that follows a standard endpoint use javascript to base64 encode the image into a string and then transfer it using your ajax request.

To convert the image, you have to use the browsers file api:

// Convert file to base64 string
export const fileToBase64 = (filename, filepath) => {
  return new Promise(resolve => {
    var file = new File([filename], filepath);
    var reader = new FileReader();
    // Read file content on file loaded event
    reader.onload = function(event) {
      resolve(event.target.result);
    };

    // Convert data to base64 
    reader.readAsDataURL(file);
  });
};

// Example call:
fileToBase64("test.pdf", "../files/test.pdf").then(result = {
  console.log(result);
  // ##### PUT YOUR AJAX CALL HERE
});
SimonEritsch
  • 1,047
  • 1
  • 8
  • 22