Titus P
Titus P

Reputation: 959

Check response code from jquery $.get()

I know this can be done with ajax, but I want to know how this could be done using the get() shortcut...

Given this:

$.get('someurl.com', function(data, statusText, xhr) {
        $('#sometag').html(data);
    });

How could I do error checking for anything that is NOT a 200? The api I am accessing returns 204s regularly if the request was valid but had no useful data to return.

Upvotes: 0

Views: 3686

Answers (2)

Megha
Megha

Reputation: 631

Fiddle link - http://jsfiddle.net/smegha11/6xu3K/

You can use xhr.status property to check response code

$.get('someurl.com', function(data, statusText, xhr) {
    if(xhr.status==200)
    {
       $('#sometag').html(data);
    }
});

Upvotes: 3

Merlin
Merlin

Reputation: 4917

Using callback methods

The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain 
multiple .done(), .fail(), and .always() callbacks on a single request.

Example

$.get( "someurl.com", function() {
  Console.log( "success" );
}).done(function() {
    Console.log( "second success" );
  }).fail(function() {
    Console.log( "error" );
  }).always(function() {
    Console.log( "finished" );
  });

Check documentation for $get

And here is which paramters each function is recieving

jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Documentation for jqXHR objects

Upvotes: 0

Related Questions