$.get() AJAX call not being able to handle server response
This might spund a little bit funny, didn't even know how to put the title at first. It could be due to long hours of work or I'm just doing something wrong.
I have a file, say comment.php, which contains something similar to:
var params = $('form#myform').serialize();
$.get("/ajax/file.php?"+params, function(data){
if (data == 'error') {
$('#message').html('Error');
} else if (data == 'success') {
$('#message').html('Success');
}
});
I checked it with firebug and everything is ok, no JS errors, the file is being called and returns either 'error' either 'success', but still, in the body of the ajax call data doesn't match the server response. I then changed
if (data == 'error') {
$('#message').html('Error');
} else if (data == 'success') {
$('#message').html('Success');
}
with
if (trim(data) == 'error') {
$('#message').html('Error');
} else if (data == 'success') {
$('#message').html('Success');
}
where trim() is a function I wrote that removes any spaces before or after the string. I also tried wit the file being called echoing numbers and making the check with jQuery like:
if (data == 1) {
$('#message').html('Error');
} else if (data == 'success') {
$('#message').html('Success');
}
with no results. If I only alert(data) everything looks fine tough. Both files are on the same domain. My code is exactly as in the example just tha开发者_StackOverflow中文版t I have more if/else conditions and one of them should allways match (it does if I look in firebug). I also tried using a switch statement with no result.
I've been using this method for some time now and never had any problems. Ideas?
The .get()
callback callback uses 3 arguments:
- the data
- the status
- the XMLHttpRequest
So, you're method should work. Make sure you pay attention to capitalization, punctuation, and whitespace.
I would try and get more info about data
to pinpoint the problem:
var params = $('form#myform').serialize();
$.get("/ajax/file.php?"+params, function(data){
alert("Type: " + typeof.data +
"\nContents: ==>" + data + "<==" +
"\nTrim: ==>" + $.trim(data) + "<=="); // get more info
});
Note that jQuery has a $.trim()
function
You don't have to append the serialized data to the query string like that. $.get() will take three arguments, one of them is a serialized (query string) version of the data or a hash. However, that is not why you are here.
The data is just whatever the php page printed out. Are you actually printing out the word "error" or "success" from that page? If not, then what you are trying to do is not going to work.
The success callback takes three arguments: data, textStatus (response), and xhr. How about:
$.get("/ajax/file.php", $("#myform").serialize(), function (data, status) {
if (status == 'error') {
$('#message').html('Error');
}
else if (status == 'success') {
$('#message').html('Success');
}
});
精彩评论