This is somewhat related to other similar questions:
jquery ajax returns error but is success
jquery .ajax always returns error - data being added to database
Jquery Ajax Call always returns error
However, my problem doesn't seem to be the data:"json"
issue.
My code is a simple POST request to a server and, for testing purposes, it is always returning 200 OK.
If I run the jquery code directly after document ready, it works just fine and calls the success
function.
But if I attach it to a on("click")
button event, it always return the error function. Nothing has changed on the server and I can see on the console that the right resource is being called.
My main code is located on a js file:
var myObj = function(){
var url = "myURL";
this.functionINeed = function(data, cb) {
ajaxPost(url, data, cb);
};
function ajaxPost(url, data, cb){
$.ajax({
"url" : url,
"contentType" : "application/json; charset=UTF-8",
"data" : data,
"type" : "POST",
"success" : function(serverData, textStatus, jqXHR){
cb(null, {
"serverData" : serverData,
"textStatus" : textStatus,
"jqXHR" : jqXHR
});
},
"error": function (jqXHR, textStatus, errorThrown) {
cb({
"jqXHR" : jqXHR,
"textStatus" : textStatus,
"errorThrown" : errorThrown
});
}
});
};
}
//I initialize the object directly on the js file
MyObj = new myObj();
Then, the first scenario: call the function directly on page load:
var data = {
"action" : "someaction",
"code" : "somecode"
}
MyObj.functionINeed(JSON.stringify(data), function(err, response){
if(err){
alert(err.errorThrown);
return err;
}else{
alert(response.textStatus);
return response;
}
});
This works fine: the server is called, the content is returned and JQuery calls the success
function.
However, if I attach this code to a button event, it always returns the error
function. I am monitoring the server and I am sure it is returning the correct data.
$("#myButton").on("click", function(){
var data = {
"action" : "someaction",
"code" : "somecode"
}
MyObj.functionINeed(JSON.stringify(data), function(err, response){
if(err){
alert(err.errorThrown);
return err;
}else{
alert(response.textStatus);
return response;
}
});
});
For the records, my server is Node.js with Sails.js, but this doesn't seem to matter.
The many similar questions are somehow related to the data:"json"
issue, but I've removed it and the most weird is that the behavior only happens when you attach the code to an event.
I would suspect there is some kind of scoping issue involved (object being instantiated on the file, for ex.), but the server is being correctly called every time. I just can't understand why JQuery interprets all responses as errors (and empty server data).
What am I doing wrong here?
See Question&Answers more detail:
os