Reputation: 181
I have form, with ajax, that contains a textarea and upload file field. I can submit only one of them. How can I fix that?
I want to send "info" + "filesData" to the server. Please advise.
AJAX :
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
alert(files_data);
var act = 'add';
var $form = $("#addCommentForm");
var info = $form.serialize();
info += '&act=' + act ;
alert(info);
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: files_data,
success: function(data)
{
// alert(data); // show response from the php script.
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false;
});
});
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-8 col-xs-12">
<textarea class="form-control" name="post[text]"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-xs-12">
<input type="file" class="form-control" name="file" id="files">
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<a class="btn btn-primary" id="submit">submit</a>
</div>
</div>
</form>
PHP
print_r ($_FILES);
print_r ($_POST);
Upvotes: 1
Views: 41
Reputation: 1946
Before the AJAX call,the data you are sending is not in the right format.Probably that's the reason you are not getting the values in the backend.Try something like this.
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('textarea', $("#addCommentForm").find("textarea").val());
And in the ajax call,the data to passed should be,
data: form_data,
Upvotes: 1