N
N
Neoliz2015-11-17 12:29:28
JavaScript
Neoliz, 2015-11-17 12:29:28

Django + Ajax Is the request correct?

Good afternoon dear forum users. I ask you not to throw tomatoes, I'm just learning. Problem with ajax requests. More precisely, as I understand it, they are lost or do not go there. Because on success, my JS reloads the page, it reloads, i.e. the script is executed and sent. And here record in a DB does not change.
CRM my application is located at {{url}}/crm. And it already has subtabs, i.e. {{url}}/crm/my_work is the path of the tab I dropped here. Please explain what's what, and with a complete code example or correction of mine, please, so that I can figure it out. I am attaching the code:
views.py

def NBEdit(request):
    if request.method == "POST" and request.is_ajax():
        MD = MyDela(
            pk=request.POST.post("id", ""),
            name=request.POST.post("name", "")[:250],
            information=request.POST.post("info", "")
        )
        MD.save()
        return HttpResponse("ok")
    else:
        return HttpResponse("bad")


models.py
class MyDela(models.Model):
    name = models.CharField(max_length=250)
    kr_info = models.CharField(max_length=300)
    date_firstly = models.DateTimeField(auto_now_add=True)
    date_edit = models.DateTimeField(auto_now=True)
    information = models.TextField()
    status = models.IntegerField()
    user = models.ForeignKey(User)


urls.py of my application, NOT the ENTIRE PROJECT
urlpatterns = patterns('',
    # ex: /cab Klients/
    url(r'^$', views.main, name='crm_main'),
    url(r'^my_work/new', views.ValidLoginMain, name='crm_new_NB'),
    url(r'^my_work/newNB/', views.NBEdit, name='crm_NBEdit'),
)


n_b_new.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <div class="new_notebook">
        <form method="POST">
        {% csrf_token %}
            <div class="new_head_notebook" id="name" contentEditable="true">
                {{MD.name}}
            </div>
            <div class="save"><input id="save" type="button" value="Сохранить" onclick = "zapros();"/></div>
            <div class="new_information_notebook" id="information" contentEditable="true">
                {{MD.information}}
            </div>
            <div style="display:none" id="pk">{{MD.id}}</div>
        </form>
    </div>


    <script>
function zapros() {
//
    var name = document.getElementById("name").innerHTML;
    var info = document.getElementById("information").innerHTML;
    var id = document.getElementById("pk").innerHTML;
//
// Если поля заполнены, отправляем их значения
    if (true) {
        $.ajax({
            url: "{{url}}/crm/my_work/newNB/",
            type: 'POST',
            dataType:"html",
            data: {
                "name": name,
                "info": info,
                "id": id,
            },
            error: function() {
                alert('Ошибка получения запроса');
            },
// При успехе очищаем поля и меняем кнопочку
            success: function(data) {
             location.reload(); // для проверки, что скрипт работает
            },
// 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>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pinkevich, 2015-11-17
@pinkevich

Change request.POST.post("id", "") in the view to request.POST.get("id", "") (and the same for everyone else)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question