Ошибка ajax запроса что это

Добрый вечер дорогие форумчане. Подскажите пожалуйста, почему при попытке отправить 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/')

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

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.

I have the following bit of code which I’m just trying out by running in firebug

$.ajax({
  type:"POST",
  url:"http://mpdomain/WebService.asmx/Operation",
  data: "{'parameter1': '44906'}", 
  contentType: "application/json;charset=utf-8",
  dataType: "json",
  success: function(data) { alert("succsess") },
  error: function(e, ts, et) { alert(ts) }
})

In theory it should work. However the error handler is triggered, and ts is simply set to «error». How do I get more detail about what’s gone wrong?

asked Feb 5, 2010 at 19:10

George Mauer's user avatar

George MauerGeorge Mauer

118k131 gold badges383 silver badges613 bronze badges

1

To see the error message from an AJAX request, you can do something like this:

$.ajax({
  type:"POST",
  url:"http://mpdomain/WebService.asmx/Operation",
  data: "{'parameter1': '44906'}", 
  contentType: "application/json;charset=utf-8",
  dataType: "json",
  success: function(data) { alert("success") },
  error: function(ts) { alert(ts.responseText) } // or console.log(ts.responseText)
});

Note that, inside the error function, you get the responseText.

Pablo Alexis Domínguez Grau's user avatar

answered Feb 5, 2010 at 19:11

ozsenegal's user avatar

3

The error message jQuery gives you is not very descriptive. It can either be «timeout», «error», «notmodified» or «parsererror.» http://api.jquery.com/jQuery.ajax/ so what you can conclude is that it’s not a timeout, not modified or parse error that you are getting.

Make sure in Firebug you see the request set to the correct address and the correct data is being set. You can also view the response so if you also have access to the server code a quick and dirty way is just to echo what is going on server side and view the response with Firebug.

Also I’m not sure if this is an issue but try to set the data to {parameter1: 44906} (basically remove the quotes so you are passing in an object and not a string).

answered Feb 5, 2010 at 19:19

jhchen's user avatar

jhchenjhchen

14.4k14 gold badges63 silver badges91 bronze badges

Let’s say I have the following jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   }
 });

Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?

My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
       if (result.error == "true") 
       {
           alert("An error occurred: " & result.errorMessage);
       }
       else 
       {
           // Do stuff
       }
   }
 });

This feels a bit clunky to me, but it works. Is there a better alternative?

asked Jan 2, 2009 at 18:12

Kevin Pang's user avatar

Kevin PangKevin Pang

41.2k38 gold badges121 silver badges173 bronze badges

Personally, I have similar code to the following code in my library.

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

jQuery docs Ajax/jQuery.ajaxSetup

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400’s (which is always associated with errors). Once the Ajax request receives this it will trigger your error function. This also means that you do not have to define an error: call in every $.ajax call.

header('HTTP/1.0 419 Custom Error');

Quote from w3.org header information

Error 4xx, 5xx
The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational.
The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

answered Jan 2, 2009 at 19:54

Asciant's user avatar

1

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   },
   error: function(request,status,errorThrown) {
        // There's been an error, do something with it!
        // Only use status and errorThrown.
        // Chances are request will not have anything in it.
   }
 });

answered Jan 2, 2009 at 18:26

Salty's user avatar

SaltySalty

6,6883 gold badges33 silver badges31 bronze badges

2

Doesn’t the jQuery ajax function accept one more parameter at the end, a callback for failed calls? If so, just add a fail:function(...){..} after the success callback.

answered Jan 2, 2009 at 18:16

rodbv's user avatar

rodbvrodbv

5,2144 gold badges31 silver badges31 bronze badges

2

Return an error code on the server side using the HTTP error the best equates to what the error is. Then use the error callback. This will also allow you to show errors given by your webserver.

answered Jan 2, 2009 at 18:16

Adam Peck's user avatar

Adam PeckAdam Peck

6,9403 gold badges23 silver badges27 bronze badges

It’s pretty late to answer this question but I think It will be beneficial to some one using es6 and jquery 2.2.

I generally follow this (deferred approach) in my code

sendAjaxRequest(URL, dataToSend) {
    return $.ajax({
        type        : 'POST',
        url         : URL,
        data        : JSON.stringify(dataToSend),
        dataType    : 'json'
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
},

I have attached a deferred fail method which will be called if some error occurs. It is an alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method in latest jquery.

Next from the place of calling sendAjaxRequest I use then jquery promise callback

sendAjaxRequest(URL, dataToSend)
.then(
     (success) => {
     },
     (error) => {
     }
);

It will call success or error function based on the response received from server.

answered Jul 6, 2016 at 9:31

WitVault's user avatar

WitVaultWitVault

23.5k19 gold badges103 silver badges133 bronze badges

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 }

Понравилась статья? Поделить с друзьями:
  • Ошибка alternator рено магнум
  • Ошибка ais расшифровка
  • Ошибка ajax запроса ошибка сервера 500
  • Ошибка ajax запроса parsererror
  • Ошибка alternator workshop что обозначает