In the below code, I’m able to transfer data but when I use the function append to transfer file and data it’s not working. Can someone tell me how to transfer file from upload? Looking forward to some help
$(document).ready(function() {
var loader = '<img src="../assets/media/loader.gif" />';
$('#submit').click(function() {
confirm("Do you really want to send messages?");
$('.loading').html(loader).fadeIn();
var msg_area_cst = $('textarea[name=msg_area_cst]').val();
var num_cst = $('textarea[name=num_cst]').val();
var form_data = new FormData();
form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
form_data.append('upload', $('input[name=upload]'));
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
});
});
2
Answers
The problem is because you correctly declare a
FormData
object, but then in the next line overwrite it immediately with a string.You need to
append()
all data to the FormData object. In addition you need to provide the file data to theappend()
method, not the jQuery object referencing theinput type="file"
control.That being said, you can make this much more simple if the controls you’re reading the values from are contained in a
form
element. Then you can use thesubmit
event of that form and pass a reference to it to the FormData constructor.Also you don’t do anything with the result of the
confirm()
I assume you want to stop the form submission ifCancel
is clicked, which the above example now does usingpreventDefault()
.Finally, using
html == 1
is very unreliable. Firstlyhtml
will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there’s any whitespace included. I’d strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a ‘success’ flag.With all that said, try this:
Try this ajax code