jQuery $.post request failing
I'm sending a $.post request to php with jQuery. The jQuery code looks like this:
$('form').submit(function() {
username = $('input[name="username"]').val();
alert(username);
$.post('/ajax/new_us开发者_运维百科er.php', {username:username}, function(data) {
alert(data);
});
});
In PHP, I'm just trying to do this for now:
<?php
echo $_POST['username'];
?>
The first alert in jQuery worked and prints the correct value, however the alert(data)
always alerts and empty string ("").
The file path is correct. I'm doing many other AJAX requests on my site that work perfectly so I'm not sure what makes this one so different. Any help is greatly appreciated!
So. The answer was adding a
return false;
at the end of the submit() event.
should not
$.post('/ajax/new_user.php', {username:username}, function(data) {
alert(data);
});
be
$.post('/ajax/new_user.php', {"username":username}, function(data) {
alert(data);
});
Try replacing
{username:username}
with
{'username':username}
If that doesn't work, replace the contents on your PHP file with:
<?php
print_r($_POST);
?>
So you can see if you're even getting the data.
Pixeline's comment solved my problem, all I had to do was return false
at the end of the submit.
精彩评论