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>
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.
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.
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.
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...
}
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With