Ajax выдает ошибку

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?

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

var link = "http://www.myapp.net/..."

$.ajax({
    url: link,
    cache: false,
    async: false,
    success: function(html){

    },
    error: function(){

    }
});

The result of the request is either an empty page or a page with just a number. So error callback actually should never be triggered, as long as the request does not fail.

But I always get the following error

alert(jqXHR + "-" + textStatus + "-" + errorThrown);

enter image description here

Here is some information about the error code in the picture

I run my project on localhost. The link in the ajax code points to another project on the web.

Any ideas?

asked Feb 26, 2011 at 12:38

DarkLeafyGreen's user avatar

DarkLeafyGreenDarkLeafyGreen

69.4k131 gold badges383 silver badges601 bronze badges

5

The error callback is executed if the ajax call can’t be completed — i.e. if the url is on a different domain (or if you are running it from a local file), if the request timeouts, or if the server responds with an error code.

I’m guessing it’s a domain (same-origin) policy error

Update: If you want to do cross-domain Ajax, check out James Padolsey’s jQuery snippet for just that (uses Yahoo!s public proxy to make all jQuery Ajax calls cross-domain)

answered Feb 26, 2011 at 13:22

Jens Roland's user avatar

Jens RolandJens Roland

27.5k14 gold badges83 silver badges104 bronze badges

3

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.

Как посмотреть какие ошибки показывается, когда ajax не выполняется правильным образом.

Одна из причин почему на WordPress может не работать ajax, это когда он не разрешен незарегистрированным пользователям. Он будет вызвать ошибку 400 Bad Request.

jQuery

Для jQuery ошибки можно увидеть так:

error: function( xhr, textStatus ) {
    alert( [ xhr.status, textStatus ] );
},

или так:

error: function (e) {
    console.log(e);
},

JavaScript

            if(request.readyState === 4) {
                if(request.status === 200) {
                } else {
                    console.log(»Произошла ошибка при запросе: ‘ +  request.status + ‘ ‘ + request.statusText);
                }
            }

Как вариант, можно посмотреть что именно выводится

            if(request.readyState === 4) {
                if(request.status === 200) {
                } else {
            console.log(‘Произошла ошибка при запросе: ‘ + request.responseText);
                }
            }

Понравилась статья? Поделить с друзьями:
  • Ajax http ошибка 500
  • Ajax error вывод ошибок
  • Ajax 502 ошибка
  • Al006 ошибка delta
  • Aisino v71 ошибка печати