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 :)
You're not clear about what the problem is. At the beginning you say
Somehow, I've broke it, and now it doesn't even touch the function(data)
but then you say that jQuery is not recognizing your JSON, which means the callback function was invoked. You need to test each phase of the process to discover your error. Browser console is a must for debugging in this case.
Test cases:
is the server returning anything? If not
If the server is returning something but it is not being parsed correctly.
To test any of this it is fundamental that you are familiar with the browser console. Chrome Network Panel or Firebug Net Tab
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
});
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.