Marc-André Lafortune
Marc-André Lafortune

Reputation: 79612

Why won't jQuery eval the response from ajax script when status code is failure

I have a simple ajax request with data-type: 'script'.

If the response's status code is 200, the returned javascript gets executed fine. If it is an error code like 500 or 403, no execution takes place.

I've re-read the doc 3 times:

"script": Evaluates the response as JavaScript and returns it as plain text. ...

This doesn't state it is conditional on success or any other condition.

As my server is responding with a response type of "text/javascript", I would have assumed that jQuery would handle that content type (i.e. evaluate it) even if it responded with a '500' status code (i.e. "hey, I couldn't do what you asked me to do")

Is this an issue with jQuery? Or is this the expected behavior and the documentation is incomplete?

Upvotes: 1

Views: 600

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

As of version 1.5 ajax calls return a deferred object.

So you can use

$.ajax({/*options*/})
  .done(function(data, status, jqxhr){ alert("$.ajax completed!"); })
  .fail(function(jqxhr, settings, exception){ alert("$.ajax failed!"); });

note the actual script will be evaluated before the .done method is called, when a successful request occurs

Upvotes: 1

Related Questions