Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error In $.get()

Tags:

jquery

ajax

I have a jquery code in which I am using get() and calling some remote url/file. Now I want to know what the best way is to handle errors from this.

What I am doing is:

   $(document).ready(function() {
        $.ajaxSetup({
            error: function(x, e) {

                if (x.status == 0) {
                    alert(' Check Your Network.');
                } 
                   else if (x.status == 404) {
                alert('Requested URL not found.');

                } else if (x.status == 500) {
                    alert('Internel Server Error.');
                }  else {
                    alert('Unknow Error.\n' + x.responseText);
                }
            }
        });

        $.get("HTMLPage.htm", function(data) {
            alert(data);
            $('#mydiv').html(data);

        });
    });

This is working fine.But want to know is there any better way of doing this?

ref:http://www.maheshchari.com/jquery-ajax-error-handling/

like image 792
Wondering Avatar asked Feb 01 '10 09:02

Wondering


People also ask

How do you handle errors in catch block?

You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed. Finally block may not get executed in certain exceptions.

How do you handle errors in JavaScript?

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.

How do you return an error in JavaScript?

In JavaScript error message property is used to set or return the error message. Return Value: It returns a string, representing the details of the error.


3 Answers

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise.

var jqxhr = $.get( "example.php", function() {     alert( "success" ); }) .done(function() {     alert( "second success" ); }) .fail(function() {     alert( "error" ); }) .always(function() {     alert( "finished" ); }); 
like image 113
joseantgv Avatar answered Oct 22 '22 23:10

joseantgv


Using $.ajaxSetup is global for all ajax calls. Because the $.get function doesn't have any error callbacks, defining an error handler in $.ajaxSetup is the only way to handle errors. If you use $.ajax, you can define the error handler in the $.ajax call like this

$.ajax({   url: "HTMLPage.htm",   success: function(data) {     alert(data);     $('#mydiv').html(data);           },   error: function(XMLHttpRequest, textStatus, errorThrown) {      if (XMLHttpRequest.status == 0) {       alert(' Check Your Network.');     } else if (XMLHttpRequest.status == 404) {       alert('Requested URL not found.');     } else if (XMLHttpRequest.status == 500) {       alert('Internel Server Error.');     }  else {        alert('Unknow Error.\n' + XMLHttpRequest.responseText);     }        } }); 

This is specific to only this ajax call, that way you can have more specific error messages. But using the global error handler works just as well.

You could define your functions outside of the $(document).ready() like this

$(document).ready(function() {     $.ajaxSetup({         error: AjaxError     });      $.get("HTMLPage.htm", GetSuccess); });  function AjaxError(x, e) {   if (x.status == 0) {     alert(' Check Your Network.');   } else if (x.status == 404) {     alert('Requested URL not found.');   } else if (x.status == 500) {     alert('Internel Server Error.');   }  else {      alert('Unknow Error.\n' + x.responseText);   } }  function GetSuccess(data) {   alert(data);   $('#mydiv').html(data); } 
like image 20
Alpha Codemonkey Avatar answered Oct 22 '22 23:10

Alpha Codemonkey


copy/paste from http://api.jquery.com/jQuery.ajax/:

statusCode(added 1.5) {}
A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({
  statusCode: {404: function() {
    alert('page not found');
  }
});

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

like image 26
Jasper De Bruijn Avatar answered Oct 22 '22 23:10

Jasper De Bruijn