How To Use $.ajax() For Input Field Text And File Upload?
This is my code $.ajax({ type: 'post', url: '../lib/upload.php', data: n
Solution 1:
It's not as simple to pass files and other data, such as text, together in the same POST request. The only way to achieve that is making multipart/form-data request.
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Solution 2:
I use ajaxForm to upload files asynchronously via ajax, it is much easier than trying to implement your own.
Solution 3:
For a cross browser solution I think it is better to use
$("#form_id").ajaxSubmit();
Solution 4:
You can use FormData to pass the File. and processData,contentType set to false compulsory. because you are not going to process file in client side.
// Create a formdata object and add the filesvar data = newFormData();
$.each(files, function(key, value)
{
data.append('myFile', value); //No I18N
});
$.ajax({
url: '/your-url',
type: 'POST',
data: data,
cache: false,
dataType: 'json', //No I18NprocessData: false, // Don't process the filescontentType: false, // Set content type to false as jQuery will tell the server its a query string requestsuccess: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
OR you can send file with data as following:
$( '#formId' )
.submit( function( e ) {
e.preventDefault();
$.ajax({
url: '/your-url',
type: 'POST',
data: newFormData( this ),
cache: false,
dataType: 'json', //No I18NprocessData: false, // Don't process the filescontentType: false, // Set content type to false as jQuery will tell the server its a query string requestsuccess: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
});
Post a Comment for "How To Use $.ajax() For Input Field Text And File Upload?"