1

I'm using javascript's 'formData' to send image files with ajax. How can I attach other data to formData, for example a text string?

JS:

$("#post-image").click(function(){
    $.ajax({
        url: "../../build/ajaxes/upload-photo.php",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
});

PHP:

In my PHP I can access the image by using $_FILES["images"]. I don't know what to use for my additional data passed with formdata.

Don P
  • 60,113
  • 114
  • 300
  • 432

3 Answers3

3

If you want to add parameters to FormData use FormData.append

$("#post-image").click(function(){
    formdata.append('name', 'value');
    $.ajax({
        url: "../../build/ajaxes/upload-photo.php",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
});

In PHP use $_POST["name"] to get the value.

Musa
  • 96,336
  • 17
  • 118
  • 137
1

You need to submit the form as multipart. Here's a SO solution to your question: Making an HTTP POST call with multipart/form-data using jQuery?

Not an exact duplicate, so I didn't mark it as such, but it's a direct reference to the solution to your problem.

Edit: you'll notice that some of the answers reference FormData as a solution as well. Once you get the data posting properly, you can then access it with the normal $_FORM collection in PHP.

Community
  • 1
  • 1
Eli Gassert
  • 9,745
  • 3
  • 30
  • 39
0

If you have Big form with Multiple file uploads then not use MALSUP JQUERY PLUGIN .It will send all your form fields with just

  $(form).ajaxSubmit();    
Shivek Parmar
  • 2,865
  • 2
  • 33
  • 42