I'm struggling with reading post data from ajax post in my php code. I'm neither an expert PHP nor Jquery, I learn it a few weeks ago. So sorry if I dont use yet all the terminology. I serialize data from ajax because I will have more field in my form. Here for the sake of clarity, I show only one field. I'm trying to read each variable, for example comment in this case, I simply try to print_r($_POST) and I got error. I cannot see how to do, probably a converting or syntax error. I would appreciate any insights
php file
public function ajaxSave($post_id)
{
print_r($_POST);
}
jquery script
$('body').on('click','#saveComment',function(e) {
$("#comment-form").submit(function(e) {
var postData = $(this).serialize();
alert(postData);
$.ajax(
{
url : "ajaxSave.php",
type: "POST",
data : postData,
dataType:"json",
success:function(data)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error");
}
});
e.preventDefault(); //STOP default action
});
$("#comment-form").submit();
});
Form
<input id="Comment_comment" type="text" name="Comment[comment]" maxlength="140" size="60">
in Firebug
in post tag, I have
Comment[comment] mycomment
Comment[post_id] 16
Source
Comment%5Bcomment%5D=mycomment&Comment%5Bpost_id%5D=16
in HTML tag, I have
Array ( [Comment] => Array ( [comment] => for [post_id] => 16 ) )
You're expecting JSON back, but returning a print of the $_POST
superglobal, and that's a parseError.
Remove the dataType and log the printout to the console to see it
$('body').on('click', '#saveComment', function (e) {
e.preventDefault();
$("#comment-form").trigger('submit');
});
$("#comment-form").submit(function(e) {
e.preventDefault();
var postData = $(this).serialize();
alert(postData);
$.ajax({
url: "ajaxSave.php",
type: "POST",
data: postData,
success: function (data) {
console.log(data)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error");
}
});
});
And don't bind the submit event inside a click event
Replace print_r($_POST);
with echo json_encode($_POST);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.