1

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:

    $.ajax({
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    url: 'xxx.php',
    cache: false,
    success: function(data) { 
        //removed for example
    }
});

The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.

urnotsam
  • 770
  • 7
  • 24

3 Answers3

0

If you want to send data along with any file than you can use FormData object.

Send your jsonData as like that:

var jsonData = new FormData(document.getElementById("yourFormID"));

Than in PHP, you can check your data and file as:

<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
devpro
  • 16,184
  • 3
  • 27
  • 38
0

Try Using formdata instead of normal serialized json

Here's an example:

var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]); 

then in your ajax

$.ajax({
    type: 'POST',
    url: "YOUR URL",
    data: formData,
    contentType: false,
    processData: false,
    dataType: 'json',
    success: function (response) {
       CallBack(response, ExtraData);
    },
    error: function () {
              alert("Error Posting Data");
          }
    });
  • Will this work if one of my values is also a JSON object? – urnotsam Sep 30 '16 at 14:28
  • no, you will get them as a normal POST form, you could do print_r($_POST) to check the values. On the other hand, you can use FormData to add Json. for example: formData.append("JSON", YOUR_JSON_OBJ"); – TestCandidate Sep 30 '16 at 15:25
0

You can try like this also

You can visit this answer also https://stackoverflow.com/a/35086265/2798643

HTML

<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />

JS

var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields

for (var i = 0; i < files.length; i++) {
    fd.append("UploadedImage" + i, files[i]);
}

$.ajax({
    type: "POST",
    url: 'Url',
    contentType: false,
    processData: false,
    data: fd,
    success: function (e) {
        alert("success");                    
    }        
 })
Community
  • 1
  • 1
Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62