February 27, 2013
jQuery $.post not returning data
Question by Cuonic
I’m using $.post to send a form via ajax to a PHP page, which returns JSON data. Once upon a time, it worked perfectly, and the function(data) executed as normal. Somehow, I’ve broke it, and now it doesn’t even touch the function(data). I’ve tried undoing most of what I’ve done, but I still can’t find the problem.
Here’s the script :
$("#modifyhome").submit(function(event) {
if($("#modifyhome").valid()) {
event.preventDefault();
var $form = $( this ),
title = $form.find('input[name="title"]').val(),
content = $form.find('textarea[name="content"]').val();
$.post("?action=page-accueil", {"title": title, "content": content},
function(data) {
if(data['error'] == 1)
{
$().message(data['message']);
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
else if(data['error'] == 0)
{
$().message(data['message']);
$("div.jquery-message").effect("bounce", {times: 3}, 900);
}
else
{
$().message("Erreur de connexion au serveur : veuillez réessayer.");
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
}, "json"
);
}
else
{
$("[id^=qtip-]").effect("pulsate", {times: 3}, 600);
return false;
}
});
And here is what the PHP page (?action=page-accueil) returns :
{"error":0,"message":"Page modifiée."}
That all checks out as valid JSON, but it’s as if jQuery doesn’t recognize it for some reason. Any help is greatly appreciated 🙂
Answer by Starx
I used to get this problem too, I am exactly not sure of the reason why. But I have a solution that works.
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = eval("("+data+")");
//.... Then continue it
});
Or, use .parseJSON()
function to read the string as JSON, if you dont want to use eval()
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = $.parseJSON(data);
//.... Then continue it
});