There was a problem ajax error

Ответили на вопрос 4 человека. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

Добрый вечер дорогие форумчане. Подскажите пожалуйста, почему при попытке отправить ajax запрос, у меня выскакивает alert из error??? Всю голову уже сломал, весь интернет уже перерыл.
2) И почему после того как я нажимаю ок в alert у меня перезагружается страница??

шаблон

{% extends "crm/main_struct.html" %}
{% load staticfiles %}

{% block content %}

<!--ОБЯЗАТЕЛЬНО СДЕЛАТЬ ФУНКЦИЮ НА JS КОТОРАЯ БУДЕТ ВЫЧИСЛЯТЬ ОТСТУПЫ И В НУЖНОЕ МЕСТО ПИХАТЬ КОНТЕНТ САЙТОВ-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('ul.tabs_m_w').each(function() {
    $(this).find('li').each(function(i) {
      $(this).click(function() {
        $(this).addClass('active').siblings().removeClass('active');
        var p = $(this).parents('div.tabs_container_m_w');
        p.find('div.tab_container_m_w').hide();
        p.find('div.tab_container_m_w:eq(' + i + ')').show();
      });
    });
  });
})
</script>
<a href="{{url}}/crm/my_work/new/" class="add_notebook_a">
    <div class="add_notebook">Добавить</div>
</a>
<div class="tabs_container_m_w">
  <ul class="tabs_m_w">
      {% for notebook in notebookList %}
        <li class="inl-bl_m_w">
            <div class="m_w_list_head">{{notebook.name}}</div>
            <div class="m_w_list_date">{{notebook.date_firstly}}</div>
            <div class="m_w_list_kr_info">{{notebook.kr_info}}</div>
        </li>
      {% endfor %}
  </ul>

    {% for notebook in notebookList %}
  <div class="tab_container_m_w">
      <a href="" onclick="resend({{notebook.id}});" class="a_tab">
          <div class="m_w_save">
            Сохранить
          </div>
      </a>
    <div class="m_w_info_head" id="name{{notebook.id}}" contentEditable="true">{{notebook.name}}</div>
      <div class="m_w_info_info" id="info{{notebook.id}}" contentEditable="true">{{notebook.information}}</div>
  </div>
{% endfor %}

</div>

<script>
    function resend(pk){
           var name = document.getElementById('name' + pk).innerHTML.trim().replace(/<.*?>/g, "");
           var info = document.getElementById('info' + pk).innerHTML.trim().replace(/<.*?>/g, "");
           edit(name, info, pk);
    }
</script>

<script>
function edit(name, info, pk) {
// Если поля заполнены, отправляем их значения
        $.ajax({
            error: function() {
                alert('Ошибка получения запроса');
            },
    // При успехе очищаем поля и меняем кнопочку
                success: function(data) {
                 alert("Успех"); // для проверки, что скрипт работает
                },
    // CSRF механизм защиты Django
                beforeSend: function(xhr, settings) {
                    console.log('-------------before send--');
                    function getCookie(name) {
                        var cookieValue = null;
                        if (document.cookie && document.cookie != '') {
                            var cookies = document.cookie.split(';');
                            for (var i = 0; i < cookies.length; i++) {
                                var cookie = jQuery.trim(cookies[i]);
                                // Does this cookie string begin with the name we want?
                            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                break;
                            }
                        }
                    }
                    return cookieValue;
                    }
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    }
                }
            });// ajax


        return false;
    };
</script>
{% endblock %}

urls.py

urlpatterns = patterns('',
    url(r'^my_work/edit/$', views.NBEdit, name='crm_edit_NB'),
)

views.py

def NBEdit(request):
    if request.is_ajax():
        for i in MyDela.objects.filter(pk=request.POST.get("id", "")):
            i.name = request.POST.get("name", "")[:250]
            i.information = request.POST.get("info", "")
            i.save()
        #  return HttpResponse("ok")
        return HttpResponseRedirect('/crm/sites/')
    else:
        #  return HttpResponse("bad")
        return HttpResponseRedirect('/crm/zayvki/')

Прошу не кидаться помидорами, я только учусь кодить))

//Controller Method
public JsonResult Wgrid(string id, string status = null)
{
try
{
var location = db.Locations.Select(r => new LocationViewModel()
{
Id = r.Id,
Code = r.Code,
Description = r.Description,
Address1 = r.Address1,
Address2 = r.Address2,
City = r.City,
ZipCode = r.ZipCode,
Contact = r.Contact,
Phone = r.Phone,
Extension = r.Extension,
Fax = r.Fax,
Email = r.Email,
SMS = r.SMS,
Latitude = r.Latitude,
Longitude = r.Longitude
}).Take(1000).ToList();
LocationDto data = new LocationDto();
data.status = «success»;
data.total = location.Count;
data.records = location;
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw;
}
}

////////View Method

$(‘#wgrid’).w2grid({
name: ‘grid’,
autoLoad: false,
limit: 100,
//url: ‘/Locations/Wgrid’,
cache: false,
data: «{}»,
contentType: «application/json; charset=utf-8»,
show: {
toolbar: true,
footer: true,
},
columns: [
{ field: ‘Id’, caption: ‘Id’, size: ‘30%’, sortable: true }, //Id

        { field: 'Code', caption: 'Code', size: '50%', sortable: true },                   //Code
        { field: 'Description', caption: 'Description', size: '70%', sortable: true },     //Description
        { field: 'Address1', caption: 'Address1', size: '70%', sortable: true },    //Address1
        { field: 'Address2', caption: 'Address2', size: '70%', sortable: true },    //Address2
        { field: 'City', caption: 'City', size: '70%', sortable: true },            //City
        { field: 'ZipCode', caption: 'ZipCode', size: '30%', sortable: true },      //ZipCode
        { field: 'Contact', caption: 'Contact', size: '70%', sortable: true },      //Contact
        { field: 'FormattedPhone', caption: 'FormattedPhone', size: '70%', sortable: true }, //FormattedPhone
        { field: 'Extension', caption: 'Extension', size: '70%', sortable: true },           //Extension
        { field: 'FormattedFax', caption: 'FormattedFax', size: '70%', sortable: true },     //FormattedFax

        { field: 'Email', caption: 'Email', size: '70%', sortable: true },              //Email
        { field: 'SMS', caption: 'SMS', size: '70%', sortable: true },                  //SMS
        { field: 'Latitude', caption: 'Latitude', size: '70%', sortable: true },        //Latitude
        { field: 'Longitude', caption: 'Longitude', size: '70%', sortable: true },      //Longitude
        ],
  });

w2ui['grid'].load('/Locations/Wgrid');

This function basically generates unique random API key’s and in case if it doesn’t then pop-up dialog box with error message appears

In View Page:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "rn" + xhr.statusText + "rn" + xhr.responseText);
                }

        });
    });
  });
</script>

From Controller:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails.
The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are «timeout», «error», «abort», and «parsererror». When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as «Not Found» or «Internal Server Error.» As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

This topic is: not resolved

  • This topic has 9 replies, 4 voices, and was last updated 8 years, 2 months ago by .

Viewing 10 posts — 1 through 10 (of 10 total)

  • Author

    Posts

  • October 31, 2014 at 3:33 pm #12914

    Help! I’m getting this message when submitting forms: There was a problem An Ajax error occurred.

    I have no idea where to go from here, as I’ve used this script many times and I’ve never had this problem. It was working fine on my development site, but now it’s not working on the production site. These are both hosted on GoDaddy Linux servers. The PHP versions were different, so I made them the same, but that didn’t do anything. I removed the jQuery, plugins.js and scripts.js files and the form does go through, but it takes the user to another page with the success message.

    The only other difference between these two sites is that the production site (level1analytics.com) has an SSL certificate. The dev site is at lshdinteractive.com/level1

    Thanks.

    October 31, 2014 at 5:20 pm #12915

    I just realized that the notification emails are going through to the recepient even though that Ajax error message comes up. Not sure what the best course of action is, but I’m thinking I might just be able to eliminate that message altogether, and put in a success message. I’m looking at plugins.js, but I’m not 100% on how to make that happen. Thanks.

    November 3, 2014 at 5:24 pm #12923

    You don’t have permission to view this content. Please log in or register and then verify your purchases to gain access.

    November 4, 2014 at 9:16 pm #12949

    Hi I am getting the same error, There was a problem An Ajax error occurred.

    I am not running WordPress, it is a flat build.

    It worked on my server but when uploading to the clients server I get the error, but the form still sends.

    Thanks,

    Kevin

    *sorry this was my fault of not updating the URL of the resources. It was loading the form from my staging server

    • This reply was modified 8 years, 3 months ago by multiplestates. Reason: Was not an issue with the form, but a user error

    November 4, 2014 at 9:57 pm #12951

    Mine is also not WordPress, I’m using the PHP version.

    November 5, 2014 at 6:35 pm #12963

    I’m finding that since the production site now has an SSL cert, certain things are breaking (My development site was not under SSL). For example, I’ve had to edit absolute links to resources by removing the ‘http:’ at the beginning of links. Also, I found that some of my jQuery scripts weren’t working until I removed the ‘$(document).ready(function(){‘ surrounding the code. Could one of these or something like this be affecting the form function?

    Thanks.

    November 6, 2014 at 8:09 am #12970

    You don’t have permission to view this content. Please log in or register and then verify your purchases to gain access.

    November 7, 2014 at 2:55 pm #12984

    Thanks, I’ll try to get a test page up soon.

    November 13, 2014 at 2:33 pm #13035

    How do we do the debug and troubleshoot, what we can do if we turn the debug?

    Kelvin

    November 17, 2014 at 1:06 pm #13057

    You don’t have permission to view this content. Please log in or register and then verify your purchases to gain access.

  • Author

    Posts

Viewing 10 posts — 1 through 10 (of 10 total)

  • You must be logged in to reply to this topic.

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

Documentation Menu

Many pages send AJAX requests to a server.
Because this relies on the cooperation of the server and the network between the client and the server,
you can expect these AJAX errors:

  • Your JavaScript program receives an error response instead of data;
  • Your program has to wait too long for the response. You can’t have the user wait indefinitely for some data to load.
  • Your program has to wait longer than expected for the response. You or your marketing department may decide to
    time out after 5 seconds, and that if responses take over 2 seconds to arrive you want to know about it.

This page shows how to implement AJAX error handling with JavaScript loggers that log to the server, so you find out about these issues.

Initial code without proper AJAX error handling

Below is a fairly typical AJAX call implemented with jQuery’s $.ajax:

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST" }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message. }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 1: Add timeout

The $.ajax method lets you set a timeout in milli seconds. When a timeout happens,

  • The fail callback is called, with errorThrown set to «timeout».
  • The request is aborted, meaning that even if the response arrives later on, your done callback is not called by jQuery.
var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST",     "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout. }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 2: Log fatal message in case of error or timeout

When there is an AJAX error response or the AJAX request times out, you’ll
want to log as much information as you have, including the error message that jQuery gives you,
the url and the request data.

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout.
JL().fatal({ "msg": "AJAX error response", "errorThrown": errorThrown, "url": url, "requestData": requestData }); }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 3: Log warning message if AJAX response takes longer than expected

Record the time before making the AJAX call and compare that with the time
when the response is received to find out how long the user had to wait for the response.
Log a warning message if it took longer than expected.

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
var msBeforeAjaxCall = new Date().getTime();
$.ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter
// Send warning log message if response took longer than 2 seconds var msAfterAjaxCall = new Date().getTime(); var timeTakenInMs = msAfterAjaxCall - msBeforeAjaxCall; if (timeTakenInMs > 2000) { JL().warn({ "msg": "AJAX response took long time", "timeTakenInMs": timeTakenInMs, "url": url, "data": data, "requestData": requestData }); } }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout.
JL().fatal({ "msg": "AJAX error response", "errorThrown": errorThrown, "url": url, "requestData": requestData }); }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

By Rod McBride

jQuery has a lot of methods to define and process AJAX requests in a convenient fashion, but one useful feature added to jQuery in version 1.0 is often overlooked by developers. 

The ajaxError() method is a method that can serve as a centralized place for AJAX request error handling. In general, unexpected server responses are handled similarly as on a web page, such as when a notification or a modal dialogue appears to tell the user that something unexpected happened and the operation has failed. 

By looking at the jQuery documentation for the AJAX convenience methods, like $.post and $.get, we notice that we can attach callback methods to successful and failed AJAX calls. 

$.post(«/api/sendStuff», function () {

    //… handle success

}).fail(function () {

    //… handle failure and display notification

});

Having a way to handle errors on individual AJAX calls is a great way to fine-tune your JavaScript and deal with specific error scenarios close to their occurrences. However, being aware of a centralized AJAX error-handling routine could avoid scenarios similar to this:

$.post(«/api/operationA», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

$.post(«/api/operationB», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

$.post(«/api/operationC», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

In this scenario, the developer created a sophisticated, dynamic, single-page application driven by a collection of AJAX requests and wrote a method that processes errors thrown by those AJAX requests. Technically, there isn’t anything wrong with this solution. However, it isn’t the most elegant approach and causes a lot of repeated code fragments. 

We can get rid of all the redundant fail callbacks by defining the default behavior of the page in case an AJAX exception occurs with ajaxError(). The method needs to be attached to the document object and will serve as a centralized processing place for those types of AJAX scenarios:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   handleError(error);

});

This global handler will always fire upon an error situation regardless if there is a defined local fail callback. Consequently, the following code fragment will display both error notifications at the same time:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   showErrorNotificationA(error);

});

$.post(«/api/operationA», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   showErrorNotificationB(error);

});

To suppress the global error handler and prevent duplicate notifications requires adding some additional logic that gives more control over it.

One way to accomplish this is to define a flag in the settings of the AJAX request that determines whether the global error handler should fire.

The biggest disadvantage of this approach is that you can’t use $.post() and $.get() anymore for these kinds of requests, and we need to fall back to $.ajax() that gives more granular control over the request. Here is an example:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   if(!settings.suppressGlobalErrorHandler){

         handleError(error);

   }

});

$.ajax(«/api/operationA», {

   suppressGlobalErrorHandler: true,

   success: function(){

      //…

   },

   error: function(jqXHR, textStatus, error){

      //…

   }

});

If you’d like to learn more about the AJAX error handling or have other jQuery or JavaScript questions, contact the technology consultants at Wipfli. You can also keep reading more of our technology-focused articles here.

jQuery is the most awesome javascript library that exists. Every day, I’m finding new ways to leverage it and shorter, more efficient ways to get things done. But, while most things are easy to do, the solution is not always immediately evident. One of the things that took me a good while to figure out was how to gracefully handle AJAX errors. Anyone who’s worked with JSON requests and other AJAX calls knows that sometimes, that stuff just fails silently; you know something went wrong, but no errors were thrown. If it wasn’t for FireBug showing us 404 or 500 style errors, there’d be no evidence at all of these fails.

I’ve come up with a way to centralize my AJAX calls in a way that seemlessly handles all errors that occur either from the request connection or the JSON processing (ie. poorly formed JSON that cannot be converted back into Javascript data types). I’m not sure if this is the best of all ways, but I’m liking it. The whole concept rests on the fact that all of my system API (AJAX) calls return a uniform response with the following structure:

{
	SUCCESS: true,
	DATA: "",
	ERRORS: []
}

The Success property flags the request as having executed properly and returned the expected data. The Data property can be anything it needs to be. The Errors property is an array of any errors that need to be reported. It is only by requiring that all AJAX requests expect this that I can easily handle all errors.

In production, the following code would probably be part of some other object or integrated into the Javascript framework in a different way, but for this demo, I’m going to break out my AJAX request pipeline into its own class:

// Create an object to handle our AJAX.
function AJAX(){
	var objSelf = this;

	// This struct will cache the current XmlHTTP requests
	// so that we can reference them if a call fails.
	this.CurrentRequests = {};
}


// This handles the JSON request. This checks to see if the current
// request is already being processed and also handles any error
// wiring that is required.
AJAX.prototype.GetJSON = function( $1, $2, $3, $4 ){
	var objSelf = this;
	var strName = $1;
	var strURL = $2;
	var objOptions = $3;
	var fnCallback = $4;

	// Check to see if there are only three arguments. If there
	// are only 3, then the first one (name of request) which is
	// optional was not passed in. Shift the other arguments
	// to the appropriate variables.
	if (arguments.length == 3){

		// Name is not being used.
		strName = null;
		strURL = $1;
		objOptions = $2;
		fnCallback = $3;

	}

	// First, we have to check to see if this request is
	// already being processed. We don't want the user to
	// try and fire off multiple requests of the same type.
	// Of course, if the name is NULL, then don't worry.
	if (!strName || !this.CurrentRequests[ strName ]){

		// Store current request.
		this.CurrentRequests[ strName ] = true;

		// Make actual AJAX request.
		$.ajax(
			{
				// Basic JSON properties.
				url: strURL,
				data: objOptions,
				dataType: "json",

				// The success call back.
				success: function( objResponse ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to success handler.
					fnCallback( objResponse );
				},

				// The error handler.
				error: function( objRequest ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to fail handler.
					objSelf.AJAXFailHandler(
						objRequest,
						fnCallback
						);
				}
			}
			);

	} else {

		// This request is currently being processed.
		alert( "Request being processed. Be patient." );

	}
}


// This will handle all AJAX failures.
AJAX.prototype.AJAXFailHandler = function( objRequest, fnCallback ){
	// Since this AJAX request failed, let's call the callback
	// but manually create a failure response.
	fnCallback(
		{
			SUCCESS: false,
			DATA: "",
			ERRORS: [ "Request failed" ]
		}
		);
}

(I’m sorry the color coding doesn’t work for my Javascript files) There’s not a whole lot going on here, but let’s walk through it. First off, one thing you can do here is make sure that only one AJAX request (of a particular type) can be processed at a time. The GetJSON() method here can take 3 or 4 arguments. If you pass in the first, optional argument — the name of the request — the GetJSON() logic will make sure that it does not launch multiple instances of the same type of AJAX request at any one time. If you pass in only the three required fields, the GetJSON() method will allow parallel AJAX requests of the same type. You will see this in the demo below — I serialize my 200 requests but allow my 404 requests to happen in parallel.

The methodology that I use leverages the $.ajax() jQuery method. I used to just use the $.getJSON() method of the jQuery library, but the $.ajax() method gives us access to the Error call back method of the AJAX request. With this method and my unified AJAX response, handling errors is actually quite easy. All AJAX errors are piped through my AJAXFailHandler() method which creates a «fail» AJAX response (sets SUCCESS flag to false) and then manually executes the AJAX callback, passing in the fail response. This way, from the AJAX response handler’s point of view, it has no idea that anything has gone wrong — it only knows that it received a response object that was either flagged as a success or a failure.

Now, let’s take a look at the demo page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Handling AJAX Errors With jQuery</title>
	<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<script type="text/javascript">

		// Initialize document.
		$(
			function(){
				var objAJAX = new AJAX();

				// Get reference to the three links.
				var j404 = $( "#error-404" );
				var jNoError = $( "#no-error" );

				// Set up 404 link.
				j404
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"does-not-exist.cfm",
								{},
								Do404RequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;

				// Set up no-error link.
				jNoError
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"NoErrorRequest",
								"200.cfm",
								{},
								NoErrorRequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;
			}
			);


		// I handle the 404 request repsonse.
		function Do404RequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "404 Error!" );
			}
		}


		// I handle the no-error request repsonse.
		function NoErrorRequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "No-Error Error!" );
			}
		}

	</script>
</head>
<body>

	<h1>
		Handling AJAX Errors With jQuery
	</h1>

	<p>
		<a id="error-404">404 Error</a> &nbsp;|&nbsp;
		<a id="no-error">Success</a>
	</p>

</body>
</html>

As you can see above, we are using jQuery to hook the links up to launch AJAX calls. Each of the two links — 404 and 200 responses — has its own response handler method. These methods, check to see if the response object was successful and just alerts the user. Notice that only the 200 style request passes in the name of the request, «NoErrorRequest»; this will ensure that the 200 style requests are serialized. The 404 style request, on the other hand, does not label its AJAX requests and therefore can make as many parallel requests as it likes.

I’m sure that I will continue to evolve the way I handle these situations over time, but so far, I have been really pleased with this methodology. It completely differentiates the two types of AJAX errors — logical vs. critical — and moves all critical error handling out of the business logic of the application.

If you are curious to see what is happening at the other end of the 200.cfm request, here is that template:

<!--- Create the response. --->
<cfset objResponse = {
	Success = true,
	Data = "Good request",
	Errors = []
	} />

<!--- Serialize the response. --->
<cfset strJSON = SerializeJSON( objResponse ) />

<!--- Get the binary response. --->
<cfset binJSON = ToBinary( ToBase64( strJSON ) ) />

<!--- Stream it back. --->
<cfheader
	name="content-length"
	value="#ArrayLen( binJSON )#"
	/>

<cfcontent
	type="text/json"
	variable="#binJSON#"
	/>

As you can see, it simply creates my unified AJAX response object and streams it back to the client.

Want to use code from this post?
Check out the license.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

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);
}
});

Понравилась статья? Поделить с друзьями:
  • There was a network error please try again error 2000
  • There was a network error please check your internet connection and try again
  • There seems to have been an error initializing or updating your transaction
  • There seems to be an error in the formtabs config
  • There might be a typing error in the address