whiteletters in blankpapers whiteletters in blankpapers - 6 months ago 18
Javascript Question

How to send additionnal data in ajax request along with formData

I have a following ajax request

onChange
of file input value.

$(':file').change(function(){
var file = this.files[0];

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

var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file

$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();

if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
data:{id:id}, // what is actually not working
cache: false,
contentType: false,
processData: false
});
});


I am adding an attribute to the html tag that includes an
id
that I wish to send along with file related data.

<input type="file" name="img" data-post-id="{{entity.id}}" />


I use PHP under Symfony2 like:

if ($request->isMethod('POST')) {
$image = $request->files->get('img');

}


I need an equivalent way to get also the id.

Answer

Pass it through url,

$(':file').change(function(){
        var file = this.files[0];

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

        var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file

        $.ajax({
            url: "http://localhost/bghitn/web/app_dev.php/image/upload?id="+id,
            //...........................................................^....

            type: 'POST',           
            xhr: function() { 
                var myXhr = $.ajaxSettings.xhr();

                if(myXhr.upload){ 
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: completeHandler,
            data: formData,

            cache: false,
            contentType: false,
            processData: false
        });        
    });

Or you can use append method to add id

$(':file').change(function(){
        var file = this.files[0];

        var formData = new FormData($('form')[0]);
        formData.append("id",id);
        //...............^.......
        var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file

        $.ajax({
            url: "http://localhost/bghitn/web/app_dev.php/image/upload?",


            type: 'POST',           
            xhr: function() { 
                var myXhr = $.ajaxSettings.xhr();

                if(myXhr.upload){ 
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: completeHandler,
            data: formData,

            cache: false,
            contentType: false,
            processData: false
        });        
    });
Comments