N
N
Neoliz2015-11-24 21:13:00
JavaScript
Neoliz, 2015-11-24 21:13:00

Why does an ajax request get an error?

Good evening dear forum users. Can you please tell me why when I try to send an ajax request, I get alert from error ??? I have already broken my whole head, I have already rummaged through the entire Internet.
2) And why after I click ok in alert my page reloads??

sample

{% 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/')


Please do not throw tomatoes, I'm just learning to code))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladislav Sklyar, 2015-11-24
@timofeydeys

Your ajax request does not have a place to go for information, there is no request type (this is not critical), there is no data (the information you are sending) . All information that you send and process in the view must be placed in data.
Example

$.ajax({
            method: "POST",
            url: '/invite/',
            data: {
            'email': email.val(),
            'csrfmiddlewaretoken': CSRF_TOKEN,
            'language':lang
            },
            success: function(response, status) {
              alert(response['msg']);
              dialog.dialog( "close" );
                },
            error: function(response) {
              alert("Error");
              dialog.dialog( "close" );
            }
          });

You can also do this // CSRF Django protection mechanism like this
<script >var CSRF_TOKEN = "{{ csrf_token }}"</script>

A
Alexander, 2015-11-25
@syschel

In order for there to be no transition after the click, you need to make a "return fall" for the click function. In order to avoid an error, you need to find out what kind of error it is, and to do this, see what the server gives and what it receives, firebug in firefox or analogues in other browsers will help you with this.

N
newpy, 2015-11-25
@newpy

You return a redirect, you expect to receive html... (dataType: html - means that you are waiting for html in response). You get a redirect (the server response code will be 304 like, not 200), so success is not executed, most likely, error is executed.
And also advice to correctly formulate questions if you want to get answers. And then from the comments, I understand that the code is not quite the same.
Why then do you post such code here, with which you check something there, and then you are surprised that it does not work?
To begin with, I would remove my CSRF tokens and make a normal, simple ajax request, with a normal response from the server, instead of redirects. Would achieve success. Step by step I added my own logic, and I would check at what stage and after adding what you get not the result you expect. At the same time, you will learn to look for your mistakes. It will be more useful.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question