简体   繁体   中英

jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK

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?

After an insane afternoon trying all kinds of combinations, a light bulb went off and I figured out the problem is that my button html was inside a form .

<form>
    <button></button>
</form>

After changing to a regular div , it worked.

<div>
    <button></button>
</div>

Which is -- to me -- absolutely insane. It seems JQuery captures more information than meets the eye when sending the ajax query, and this was messing the response parsing by expecting some form encoded behavior. Does it mean I cannot have special purpose buttons inside my forms? Since I am using Bootstrap, that's "OK" because I can use the a tags for this (tested and worked). But this seems a JQuery bug ( version: 1.11.2 )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM