No data returning from ajax $.post()
I am having trouble getting any response text from my jQuery AJAX post:
$('document').ready(function()
{
$('#saveRouteTrace').click(function(){
// Build latStr and lonStr
if(saveCha开发者_StackOverflownges()) {
$.post('changeRouteTrace.php', {
id: traceRouteId
},
function(data) {
if(data.success) {
alert(data.reason);
}
else {
alert("Error: " + data.reason);
}
}, 'json');
}
});
});
I am returning a response like:
{ "success": true, "reason": "because it worked" }
from the server, but the function(data) code never executes. What am I doing wrong?
You can check using FireBug if the request is sent and if the response looks ok. If the request is sent, but you don't get a proper response, it may be easier to create a test form in HTML and post the data using that form. Debugging that is easier than using the javascript response, because you can just keep refreshing after a change and check the response in the browser.
Assuming your savechanges() function returns a value, this code snapshot works fine in my system.
$(document).ready(function(){
$('#saveRouteTrace').click(function(){
// Build latStr and lonStr
if(saveChanges()) {
$.post('stackoverflowajax.php', {
id: 9,
name:'Tsegay'
},
function(data) {
alert(data);
if(data.success) {
alert(data.reason);
}
else {
alert("Error: " + data.reason);
}
}, 'json');
}
});
function saveChanges(){
//This is a debuging code ... Make sure it return a value
return true;
}
});
This is the file on the server side. I am echoing the json file.
if(isset($_POST['id'])){
//This do not work
return '{ "success": true, "reason": "because it worked" }';
//this works fine
echo '{ "success": true, "reason": "because it worked" }';
}
精彩评论