2

I'm trying to upload a picture with ajax.

This works if I do like this:

    $("#adv_cover").change(function(e){

        e.preventDefault();

        var formData = new FormData($('#adv_form_cover')[0]);

        $.ajax({
            type: 'POST',
            url: 'edit.php',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {}
         });
    });

Then in PHP I get the data like this:

if($_FILES["adv_cover"]["name"]) {}

OK.

But now, I need to send an ID too, so this is how I do it according to some cases I found around here:

    $("#adv_cover").change(function(e){

        e.preventDefault();

        var formData = new FormData();
        formData.append('id', '1300');
        formData.append('adv_cover', $('#adv_form_cover')[0]);

        $.ajax({
            type: 'POST',
            url: 'edit.php',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {}
         });
    });

Then in PHP I try to get the data like this:

$id=$_POST['id'];
if($_FILES["adv_cover"]["name"]) {}

But I don't get anything now.

I also tried to console.log both formData['id'] and formData['adv_cover'], with no success, so it seems that the problem is, at least, on the javascript side.

Note that I also tried both:

formData.append('adv_cover', $('#adv_form_cover')[0]);

and

formData.append('adv_cover[]', $('#adv_form_cover')[0]);

Thank you for your help

2 Answers 2

5

It would seem that whereas the new FormData() call accepts a HTML Form element, the .append() method does not:

append

value
   The field's value. Can be a Blob, File, or a string, if neither, the value is converted to a string.

(taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData)

So in order to send a file — when using the append method — you need to get hold of the File object, or the Blob for the file. I do not have a set-up available to test at the moment, but you can gain access to a File object using:

$('#adv_form_cover').get(0).files[0]

or without jQuery:

document.getElementById('adv_form_cover').files[0]

So perhaps try whichever you prefer as the value for your append, using the following of its versions:

void append(DOMString name, File value, optional DOMString filename);


update

Hmmm, odd... yes, this is what I meant:

formData.append('adv_cover', $('#adv_form_cover').get(0).files[0], 'filename');

Although to work it will definitely need a file selected in the input. What does console.log() say if you log myfile?

Another thing you can try is an amalgamation of your two approaches, basically you create your form using your first example:

var formData = new FormData($('#adv_form_cover')[0]);

But then append the extra data, like so:

formData.append('id', '1300');

That may work, and was taken from the bottom of this page here:

https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

Sign up to request clarification or add additional context in comments.

11 Comments

Not sure I follow the last part. So I did this: "var myfile=$('#adv_form_cover').get(0).files[0];" and then this: "formData.append('adv_cover', myfile);" but then the javascript freezes. Please bare with me as I'm not a developer. I can manage an explanation and its logic but the more theoretical it becomes the more I get lost.
@Baylock ~ Sure thing, no problem :) one other question, what browser are you testing with?
@Baylock ~ sending data via AJAX has always had oddities across different browsers, and the File/Blob APIs are relatively new... but to be perfectly honest I was just checking that you weren't using IE8 or something ;) Modern FF, Safari and Chrome you should be fine.
@Baylock ~ If you used this formData.append(id='1300'); (and it isn't just a typo) then that will fail, it needs to be two separate parameters like formData.append('id', '1300');. However if it was a typo and you tried it correctly then I'm not sure what the issue is... personally I've only ever sent file data or post data via AJAX, not both at the same time. As a fallback you can always send certain information as part of the GET i.e. edit.php?id=1300
@Baylock ~ ah yes, sorry I wasn't clear in my comment that you could do both simultaneously.. glad it worked! Although you've now set me on a course to find out why sending extra data as post was failing ;) I'll update my answer if I find out why. Cheers.
|
-1

you can pass multiple parameters like that

$.ajax({
  type: "POST",
  url: "edit.php",
  data: { id: "ID HERE", adv_cover: "ADV COVER HERE" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
});

3 Comments

Even data coming from a file type input? Don't think so, as it needs an array of data (name, size, type,...)
buddy you can pass parameters like this $.ajax({ type: 'POST', url: 'edit.php?id=blabla&adv_cover=blabla', data: formData, processData: false, contentType: false, success: function(response) {} });
Well, as you can see with the post of EtrnalHour (read my comment there), it didn't work for me. My issue was to pass file input data along with a simple variable and your script didn't allow me to do so. Why? I don't know but it didn't work. So I had to mix post and get to achieve this and now it's ok. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.