Jquery вывод ошибки

how to jQuery ajax error function and jQuery Error Ajax message when Ajax decision passing information to a page that then returns a worth.

In this post we will show you how to jQuery ajax error function when Ajax decision passing information to a page that then returns a worth(value).

I have retrieved the self-made decision from the page however I even have coded it so it raises an erreo(bug) within the your call page(example url: "data.php"). however do we retrieve that error from the jquery? how we get jQuery Ajax Error Handling Function hear is the solution of ajax error function.

this jQuery ajax error function is very basic and easy to use with your ajax call.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data)
{
// success alert message
alert(data);
},
error: function (error)
{
// error alert message
alert('error :: ' + eval(error));
}
});

jQuery ajax error function using jqXHR

jQuery ajax error function using jqXHR in this function we can get different type ajax error like 404 page error, 500 Internal Server error, Requested JSON parse, Time out error.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data)
{
// success alert message
alert(data);
},
error: function (jqXHR, exception) {
var error_msg = '';
if (jqXHR.status === 0) {
error_msg = 'Not connect.n Verify Network.';
} else if (jqXHR.status == 404) {
// 404 page error
error_msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
// 500 Internal Server error
error_msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
// Requested JSON parse
error_msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
// Time out error
error_msg = 'Time out error.';
} else if (exception === 'abort') {
// request aborte
error_msg = 'Ajax request aborted.';
} else {
error_msg = 'Uncaught Error.n' + jqXHR.responseText;
}
// error alert message
alert('error :: ' + error_msg);
},
});

Parameters for jQuery ajax error function with jqXHR

Parameters for jQuery ajax error function with jqXHR for It actually an error object which is looks like this.

jQuery ajax error function with an validation error

jQuery ajax error function with an validation error :: If we want to inform(get error message) in frontend about an validation error try this method.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data, textStatus, jqXHR) {
console.log(data.error);
}
});

Содержание:

  • .error( handler )

    • .error( handler )
    • .error( [eventData ], handler )
  • Обсуждение
  • Примеры

.error( handler )Возвращает: jQueryversion deprecated: 1.8, removed: 3.0

Описание: Устанавливает обработчик ошибки при загрузке элементов (например отсутствие необходимой картинки на сервере).

  • Добавлен в версии: 1.0.error( handler )

    • handler

      A function to execute when the event is triggered.

  • Добавлен в версии: 1.4.3.error( [eventData ], handler )

    • eventData

      An object containing data that will be passed to the event handler.

    • handler

      A function to execute each time the event is triggered.

This method is a shortcut for .on( "error", handler ).

As of jQuery 1.8, the .error() method is deprecated. Use .on( "error", handler ) to attach event handlers to the error event instead.

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

For example, consider a page with a simple image element:

1

<img alt="Book" id="book">

The event handler can be bound to the image:

1

2

3

4

5

alert( "Handler for .error() called." )

.attr( "src", "missing.png" );

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Handler for .error() called.

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

Note: A jQuery error event handler should not be attached to the window object. The browser fires the window‘s error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

Дополнительные замечания:

  • As the .error() method is just a shorthand for .on( "error", handler ), detaching is possible using .off( "error" ).

Примеры использования

error-management2-basics

Ok, so I’m assuming you all know about Firebug and FireQuery. If you don’t these posts may help you. Firebug has a number of powerful tools that can make the previous nightmare of JavaScript debugging tolerable.

  • How to setup Firebug
  • Using FireQuery to Change Google Logo

So now you want to manage those errors better not just so that your users don’t see any errors but to also help when you are developing your scripts.

Alert()

javascript-error-alert

//alert() shows values in a popup window
alert("js is working");

Alert can be used to see if your code is actually be executed because if there are critical syntax errors in your JavaScript it won’t execute at all. Can also be used to see if a certain code block or segment is being reached.

Console.log()

javascript-error-console-log

//console.log() shows values in the firebug console window
var x = ... etc
console.log(x);

Console.log() can be very useful for showing values executed in loops and for catching events. More on this later in the post. The full range of options for logging can be seen in the Firebug Console API wiki page.

Important: make sure you enclose your firebug commands otherwise your jQuery code will only work when the console is open.

Try/Catch

//try catch example 1
try {
	$("#user").focus();
} catch(err){
	return false;
}

//try catch example 2
try {
var tmp = doSomething();
if (tmp == something.errorCondition)
throw new Error("Error condition in X");
} catch(err) {
//handle ((err && err.message) || err.toString())
} 

//try catch example 3
try {
  // code that may cause an error
} catch (e) {
  // deal with error (or not)
}
// code that runs whether or not error occurred

Override Errors for display in Firebug

You can also override jQuery.error for display in Firebug like so:

jQuery.error = console.error;

jQuery Stop Error Display

If you use jQuery event handlers, you can use a combination of window.onerror and wrapping the jQuery event handler code and on ready function with an error handling function.

  • window.onerror: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
  • jQuery event handlers: catches jQuery event errors in all browsers.
  • jQuery ready function: catches initialisation errors in all browsers.

Types of jQuery Errors (common errors)

A common error is when AJAX returns no data. This can be handled by adding error messages, see the following example of an AJAX contact form.

$("#createContact").click(function () { //Attach a click event handler to the button
    var form = $("form"); //Grab the form element from the DOM

    $.ajax({
        type: "POST", //The type of HTTP verb (post, get, etc)
        url: form.attr( "action" ), //The URL from the form element where the AJAX request will be sent
        data: form.serialize(), //All the data from the form serialized
        dataType: "json", //The type of response to expect from the server
        success: function ( data, statusCode, xhr ) { //Triggered after a successful response from server
            if ( data && data.Message ) {
            	alert( data.Message );
            }
        },
        error: function ( xhr, errorType, exception ) { //Triggered if an error communicating with server
            var errorMessage = exception || xhr.statusText; //If exception null, then default to xhr.statusText

            alert( "There was an error creating your contact: " + errorMessage );
        }
    });

    return false; //Ignore the default behavior of the button click
});
[code lang="php"]

Checking in firebug the has a StatusText field which can be used to determine the type of jQuery error.

firebug-error-management

Useful AJAX Catch Error Function

function ajaxError(request, type, errorThrown)
{
	var message = "There was an error with the AJAX request.n";
	switch (type) {
		case 'timeout':
			message += "The request timed out.";
			break;
		case 'notmodified':
			message += "The request was not modified but was not retrieved from the cache.";
			break;
		case 'parseerror':
			message += "XML/Json format is bad.";
			break;
		default:
			message += "HTTP Error (" + request.status + " " + request.statusText + ").";
	}
	message += "n";
	alert(message);
}

Further reading:

  • http://www.bennadel.com/blog/1392-Handling-AJAX-Errors-With-jQuery.htm

Понравилась статья? Поделить с друзьями:
  • Jquery validation error class
  • Jquery validate error list
  • Jquery validate error element
  • Jquery validate error custom
  • Jquery validate error class