Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add file value with jQuery serialize()

I am sorry for the weird title of the question.

I am trying to process a form using jQuery ajax which contain a file.

This is what I am trying to use..

<script>
     var file_data = $('#qfile').prop('files')[0];   
     var form_data = new FormData();
     form_data.append('file', file_data);// 
     var data = $(this).serialize();
     // Here is the problem. I sucessfully sent the file alone but I want to 
     //send all the form input values using serialize() and add formData too

</script>

I want to send the file and also all the input serialize()

Here is my ajax part...

<script>
   $.ajax({

            type : 'POST',
            url  : 'ajax/ajax-reg.php',
            data : form_data,
            processData: false,
            contentType: false,

</script>
like image 731
Hkm Sadek Avatar asked Jan 16 '17 20:01

Hkm Sadek


People also ask

What is the use of serialize () method in jQuery?

The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

What is the use of serialize ()?

Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

How do you serialize form data?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.


2 Answers

I want to send all the form input values using serialize() and add formData too

In this case serialize() won't help you, but there is a better way. Simply provide the form DOMElement to the FormData() constructor. Then all the data from the form fields (including the images) will be placed in to the FormData object. Try this:

var form_data = new FormData($('form')[0]);
$.ajax({
    type: 'POST',
    url: 'ajax/ajax-reg.php',
    data: form_data,
    processData: false,
    contentType: false,
    success: function() {
        // handle response here...
    }
});
like image 133
Rory McCrossan Avatar answered Sep 30 '22 20:09

Rory McCrossan


Using jQuery, you also can try something like this:

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

postData.append("In", $("input[name=In]").val()); // usual input
postData.append("Txt", $("textarea[name=Txt]").text()); // textarea
postData.append("File", $("input[name=File]")[0].files[0]); // file

$.post('ajax/ajax-reg.php', postData);
like image 21
simhumileco Avatar answered Sep 30 '22 19:09

simhumileco