Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .ajax() success always firing (even when server returns error code)

Tags:

jquery

ajax

I have a form that is being serialized by JQuery and posted via .ajax() to a url.

The problem is that the 'success:' function is always called, regardless of whether the server returns an error code or not.

In fact, success fires even before the server has responded (I have put a breakpoint on the server method that services the request - success fires even before this method is completed). If the server returns an error code (e.g. Status code 500) JQuery calls BOTH success and error events!

Any ideas what's going on? Here's my jquery code:

$("#a-dialog").dialog({
    autoOpen: false,
    height: 300,
    width: 400,
    modal: true,
    buttons: {
    "Submit": function() {
                $.ajax({
                  type: 'POST',
                  url: theURL,
                  data: $("#a-dialog-form").serialize(),
                  success: alert('ok!') // THIS IS ALWAYS CALLED (IMMEDIATELY)
                });
        },
    },
});

UPDATE:

This was a stupid error on my part! Thanks to blue112 for quickly pointing it out :)

like image 541
UpTheCreek Avatar asked Feb 26 '23 22:02

UpTheCreek


1 Answers

That's normal, you must pass it as a callback, eg

            $.ajax({
              type: 'POST',
              url: theURL,
              data: $("#a-dialog-form").serialize(),
              success: function(){alert('ok!');} // The function will be called upon success.
            });
like image 81
blue112 Avatar answered May 19 '23 17:05

blue112