JQuery.ajax () success always fires (even when the server returns an error code)

I have a form that is serialized by jQuery and submitted via .ajax () in the 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 is triggered even before the server responded (I set a breakpoint on the method of the server that serves the request - success is triggered even before this method is completed). If the server returns an error code (for example, status code 500), jQuery raises BOTH success and error events!

Any idea what is going on? Here is 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:

It was a stupid mistake on my part! Thanks blue112 for the quick tip :)

+4
source share
2 answers

This is normal, you should pass it as a callback, for example

  $.ajax({ type: 'POST', url: theURL, data: $("#a-dialog-form").serialize(), success: function(){alert('ok!');} // The function will be called upon success. }); 
+7
source

You need to ensure success with a function pointer, or, as usual, by passing a function definition.

What you need to do is the following:

  "Submit": function() { $.ajax({ type: 'POST', url: theURL, data: $("#a-dialog-form").serialize(), success: function (data) { alert('ok!') // THIS IS ALWAYS CALLED (IMMEDIATELY) } }); }, }, 

What happens in your case is that the warning is triggered immediately, so you will see a warning message even if the ajax request is not running at all.

+1
source

All Articles