Error while ajax request

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

Содержание

  1. Почему выскакивает ошибка при ajax запросе?
  2. Handling Ajax errors with jQuery.
  3. JQuery 3.0: The error, success and complete callbacks are deprecated.
  4. One thought on “ Handling Ajax errors with jQuery. ”
  5. Error while ajax request
  6. 7. Warning: Ajax error
  7. Meaning
  8. Diagnosis
  9. Safari
  10. Chrome
  11. Firefox
  12. Opera
  13. Resolution

Почему выскакивает ошибка при ajax запросе?

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

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

  • Вопрос задан более трёх лет назад
  • 3726 просмотров

Оценить 1 комментарий

У вашего ajax — запроса нет ютл куда обращаться за информацией, отсутствует тип запроса(это не критично), отсутствует data(информация которую отправляете) . Всю инфу которую отправляете и обрабатываете во вьюхе нужно укласть в data.

Также можно вот это //CSRF механизм защиты Django сделать вот так

Просмотрел, не тот код выкинул)))
method: «POST»,
url: ‘/invite/’,
data: <
’email’: email.val(),
‘csrfmiddlewaretoken’: CSRF_TOKEN,
‘language’:lang
>,

Эта штука есть у меня, но все равно проблема.
А почему страница перезагружается?

$.ajax( <
url: «<>/crm/my_work/edit/»,
type: ‘POST’,
dataType:»html»,
data: <
«name»: name,
«info»: info,
«id»: pk,
>,
error: function() <
alert(‘Ошибка получения запроса’);
>,
// При успехе очищаем поля и меняем кнопочку
success: function(data) <
alert(«Успех»); // для проверки, что скрипт работает
>
>);

Возвращаешь редирект, ожидаешь получить html. (dataType: html — означает что ты в ответ ждешь именно html). Получаешь редирект (код ответа сервера будет 304 вроде, а не 200), поэтому success и не выполняется скорей всего, выполняется error.

А еще совет грамотно формулировать вопросы, если хочешь получить ответы. А то из комментариев я так понял что и код не совсем тот выложен.

я редирект сделал, что бы понять, выполняется ли код во вьюхе или нет

Зачем тогда выкладываешь сюда такой код, которым ты что-то там проверяешь, и потом удивляешься что не работает?

Для начала убрал бы свои CSRF токены и сделал бы нормальный, простой ajax запрос, с нормальным ответом от сервера, вместо редиректов. Добился бы выполнения success. Поэтапно добавлял свою логику, и проверил бы на каком этапе и после добавления чего получаешь не тот результат который ожидаешь. Заодно научишься искать свои ошибки. Это будет полезнее.

Источник

Handling Ajax errors with jQuery.

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:

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:

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:

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.

One thought on “ Handling Ajax errors with jQuery. ”

thanks its helpful 🙂 many of us not aware of error block in ajax

Источник

Error while ajax request

Some times when we request to server we didn’t get proper response (HTTP Status 200) as per our expectation. For ex. we can get
1) Internal Server Error
2) Network Connection Error
3) Page Not Found Error,
4) Access Denied Error.

So if we are making call to server via http post request/simple http request directly then user will see these error in browser. But when we use AJAX service calls and if we don’t properly handle the inevitable errors (like mentioned above) then our code fails and it didn’t display anything and user get stucked. AJAX service calls are especially problematic. So to show proper error message to user we need to use proper error handling.

Even when a client-side error is thrown, most users won’t notice it and the ones who do notice won’t know what the error means or what to do next. In fact, many developers don’t notice client-side scripting errors that occur while they’re debugging their own applications!

For example : After logined in the system user open site link in new tab. Now user has opened two tab and if user logout from first tab and switch to second tab then in second tab whenever user will not refresh that page he will not be logged out. And without refresh the page if user fire an event that is AJAX based and if we didn’t used proper error handling user will get stucked because he will not get proper message, but we must show him a proper message that “Sorry!! Your session has expired. Please login again.” . Same may happen when session expired automatically after not using the system for few minutes.

So to come over this problem we will use AJAX error function.

So when ever we didn’t get “HTTP Status 200 OK” from server and get any error this response will automatically will go to error function.
1) jqXHR : This variable will contain status code and we can access by “jqXHR.status”.
2) textStatus : Response in text like Success.
3) errorThrown : Some time error may be related to parse error, timeout error so these error message will come under this variable.

1) alert : Simple. using to show error message
2) formatErrorMessage : We are using this function to parse this variable and get exact error and to show a proper message to user.

Its defined below.

Now how to handle errors in jquery load function.

Now in “HTTP Status 401 Not Authorized condition” if you want to redirect user to login page.
use

Note : bootbox.alert is a “bootboxjs” function to show alert message with proper bootstarp design popup.
http://bootboxjs.com/

You can also update error message in “formatErrorMessage” function as per your requirement and can add more exception and status code.

1) 400 : “Server understood the request, but request content was invalid.”

2) 403 : “Forbidden resource can’t be accessed.”

3) 503 : “Service unavailable.”

Also if you want to set your own “HTTP Status Code” according to your condition at server side you can use “header” function.
Ex : header(“HTTP/1.1 401 Unauthorized”);

Источник

7. Warning: Ajax error

When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response. The error given is:

DataTables warning: table > — Ajax error

where is the DOM id of the table that triggered the error.

Meaning

This occurs when jQuery falls into its error callback handler (this callback built into DataTables), which will typically occur when the server responds with anything other than a 2xx HTTP status code. For example the server might respond with 404 Not Found indicating that the file requested is not available at the given URL, or 500 Internal Error which indicates that the server encountered an error while processing the request.

DataTables will fire a specific error for the case where the request from the server is a valid return ( 200 Ok for example), but not valid JSON — see technical note 1 for more information. This error (7) indicates a general error, as stated above.

Diagnosis

If the server didn’t reply to the Ajax request with a 2xx status code, we need to know what it did reply with, so we can take corrective action. So discovering what that reply was will be the starting point for resolving the issue full.

Modern browsers all come with built in developer tools, which can be used to find out what data the server is responding to the DataTables Ajax request with. Instructions on how to do this with your browser are shown below.

Safari

1. Open preferences

2. Enable developer menu

3. Show error console

4. The error console

5. Ajax response

  1. By default Safari hides its built-in developer tools. If you don’t have a Develop menu shown in Safari it needs to be enabled. If you do, jump to step 3.
    • Open the Safari menu and select Preferences.
  2. Enable the developer menu in the Advanced tab
    • Click the Advanced tab in the Preferences window
    • Check the box for Show Develop menu in menu bar option
    • Close the preferences — the Develop menu will now be shown
  3. View the error console
    • Select the Show Error Console option from the Develop menu.
    • The developer console will show at the bottom of the page
  4. Any errors encountered on the page are shown in the developer console
    • Safari logs general Ajax errors to the developer console — in the example shown above a 404 Not Found error.
  5. Additional information can also be found in the Resources tab.
    • Click the Resources tab
    • Reload the page so Safari can capture all network requests
    • Safari will show a list of all resources (images, scripts etc) which have been loaded for the page. Locate the Ajax request that has been made to the server and click it. Safari will show detailed information about the request.
    • Note that on pages with a large number of resources, Safari will group the resources by type into folders. If this happens on your site, look for the «XHRs» folder for the Ajax requests.

Please note that these instructions were written with Safari 7 as the version used. Newer versions might have slightly different steps.

Chrome

1. Open debugger

2. Console displayed

3. Show Network tab

4. Ajax response

  1. To access the Chrome’s developer console:
    • Mac: Access the View > Developer > JavaScript Console menu option.
    • Windows: Click the Chrome menu (to the right of the address bar) and select Tools > Javascript console.
  2. The Console_ is shown at the bottom of the current browser window.
    • If a general error has occurred, it will be shown here
  3. More detailed information can be obtained from the network panel will show all of the requests made by Chrome to load the page.
    • Refresh the page to allow Chrome to capture all requests
    • Click the XHR option at the bottom of the window to reduce the requests to just the Ajax (XHR) requests.
  4. Details about the Ajax request are shown.
    • Double click the Ajax requests made, including the one which is resulting in an error — a 404 error in this case.

Please note that these instructions were written with Chrome 31 Mac as the version used. Newer versions, or those on different platforms might have slightly different steps.

Firefox

1. Open debugger

2. Network requests

3. Ajax requests

4. Ajax response

  1. To access the developer tools in Firefox:
    • Mac: Access the Tools > Web Developer > Network menu option.
    • Windows: Click the Firefox menu (top left of the window) and select Web Developer Network option.
  2. The Developer tools are shown at the bottom of the current browser window.
    • Refresh the page to allow Firefox to capture all requests
  3. The network panel will show all of the requests made by Firefox to load the page.
    • Click the XHR option at the bottom of the window to reduce the requests to just the Ajax (XHR) requests.
    • The red glowing button indicates an error occurred.
  4. Further details about the Ajax request are shown.
    • Double click the Ajax request made by DataTables to view detailed information about the request, including error information.

Please note that these instructions were written with Firefox 26 Windows as the version used. Newer versions, or those on different platforms might have slightly different steps.

1. Open debugger

2. Element inspector

3. Show Network tab

4. Ajax response

4. Ajax response

  1. To access the developer tools in IE:
    • Press F12 or,
    • Click the tools menu (top right, a cog icon) and select the F12 developer tools option.
  2. The Developer tools are shown at the bottom of the current browser window. IE will show the document tree by default.
    • Click on the Network tab to view network requests
  3. IE requires that network traffic be specifically tracked, which we want here.
    • Click the Start capturing button to capture network requests
    • Refresh the page to allow IE to capture all requests
  4. The network panel will show all of the requests made by IE to load the page.
    • Find the Ajax request made by DataTables — it will likely be at or near the bottom of the request list
    • In this case IE is showing that the file requested as not found.
  5. Details about the Ajax request are shown.
    • Double click the request to view detailed information about the request.

Please note that these instructions were written with IE 10 as the version used. Newer versions might have slightly different steps.

Opera

1. Open debugger

2. Element inspector

3. Show Network tab

4. Ajax response

  1. To access the developer tools in Opera:
    • Mac: Right click or ctrl click the document and select the Inspect element option.
    • Windows: Right click the document and select the Inspect element option.
  2. The Developer tools are shown at the bottom of the current browser window. Opera will show information about the element that was clicked on.
    • Click on the Console tab to view console messages logged by Opera
  3. The error console is shown, with logged errors displayed
    • In this case it is showing that the requested file cannot be found.
  4. Detailed information about the Ajax request can be found in the Network tab.
    • Click the Network tab in the developer tools
    • Reload the page to ensure Opera can capture all requests for the page
    • Locate the request which is in error and double click it to view detailed information.

Please note that these instructions were written with Opera 18 Mac as the version used. Newer versions, or those on different platforms might have slightly different steps.

Resolution

Once you have followed the instructions above you will know what error the server is responding with for the Ajax request.

The most common errors are:

  • 404 — Not Found.
    • The URL requested was not found on the server.
    • Check for typos in the file name in the ajax parameter and in your file on the server.
  • 500 — Internal Error.
    • The server encountered an error while responding to the request.
    • Check the server’s error log for information as to why this error occurred.
  • Origin not allowed by Access-Control-Allow-Origin.
    • A request has been made to page on a different domain from the domain which the current page has been loaded from.
    • Browsers have security measures built in to prevent loading of external scripts — for example on http://localhost you cannot Ajax load a script from http://google.com without special measures.
    • If you are using a single domain, ensure you are specifying a relative or absolute path without a domain name (i.e. don’t start the URL with http(s):// ).
    • Use JSONP or some other cross domain access technology such as a proxy script on your server.

If you are willing to accept the error (for example if you cannot alter the backend system to fix the error), but don’t want your end users to see the alert() message, you can change DataTables’ error reporting mechanism to throw a Javascript error to the browser’s console, rather than alerting it. This can be done using:

Источник

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.

@Akamaozu — I have a multisite with BuddyPress and none of my BuddyPress tables has ever caused the problem. Caveat: since I don’t know what «the problem» actually is, I do not have any grounds to assure you that your BuddyPress tables are not the cause in your case. For me, the problem was caused by an as-yet-unknown «something» in Watu (a quiz plugin) tables.

The BuddyPress «activity» table may contain all sorts of stuff that could be breaking this script, since it’s user-generated content. It would be pretty tough to guess at the root cause — I’ll leave that to the developer.

Here is my solution, as noted above. Every time I run the script on this site (and I’ve done it enough to get pretty good at it now….) I just deselect the tables that are problematic.

Through a series of trials, I ultimately identified two tables (from one plugin, which were present in multiple sites of the multisite) that were «sticking points». The script would successfully process the table just prior to the «broken» one, and then it would throw the AJAX error.

By using the «select tables» radio button and deselecting the ones that were getting stuck (the table following the «last one» that had successfully processed), I was able to get the script to complete. I will have to review those tables manually.

For me, the clue was the table that got processed just prior — I can see that table in the list as completed — then the script hangs. So I identified the NEXT table in the database as the problem child, and skipped it on the next dry run. Eventually I had a list of problem tables — all from Watu, in my case — and by skipping those for each site in the multisite, I could get through the entire run.

Note that in multisite, you may have identical tables in several sites, so you’ll have to de-select those same tables several times in the process of setting up this script to run. It’s a bear at first, but once you figure out which ones to skip, you’ll get the hang of it.

You’ll start with selecting all tables, then deselect the one that you think is the culprit. Do a dry run, and see if the script gets past that point. It might hang again on another table, but each time it goes farther, you’ve identified ONE problematic table. Note each one, and skip those each time.

Also, I had a red herring throwing me off for a while. I was getting an error like this:

The table "wpXX_wangguardreportqueue" has no primary key. Changes will have to be made manually.

just before the AJAX error. I tried skipping those tables, because I thought they were causing the AJAX error. As it turned out, they are unrelated. The script will process just fine past tables without a primary key.

For me, this injected a point of confusion and distraction to my logical process of troubleshooting, because WangGuard and Watu tables are right next to each other alphabetically. The primary key error would occur just before the AJAX error, causing me to think they were related.

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.

Понравилась статья? Поделить с друзьями:
  • Error while accepting ssl connection error 02001003 system library fopen no such process
  • Error when trying to open audio device tonelib
  • Error when trying to open audio device minihost modular
  • Error when trying to open audio device light host
  • Error when trying to connect bad healthcheck status