Snowwy
Snowwy

Reputation: 40

How to submit a form to server using ajax?

I'm trying to send a button id to my server using ajax to submit a form because I don't want to load a new page everytime I click on a button. But it isn't working and I don't know why. It donesn't even change the button thexto 'x' anymore.

I'm very new to ajax btw

Here is my script:

<script> 
    var docFrag = document.createDocumentFragment();
    for (var i=0; i < 3 ; i++){ 
        var row = document.createElement("tr") 
        for (var j=0; j < 3 ; j++){ 
                 var elem = document.createElement('BUTTON');
                 elem.type = 'button';
                 elem.id = 'r'+i+'s'+j;
                 elem.value = 'r'+i+'s'+j;
                 elem.onclick = function () { 
                    document.getElementById("klik").value = this.id;
                    document.getElementById("ID").value = this.id;
                    //document.getElementById("klik").submit();

                    $("#klik").submit(function(event){
                        event.preventDefault(); //prevent default action 
                        var post_url = $(this).attr("action"); //get form action url
                        var request_method = $(this).attr("method"); //get form GET/POST method
                        var form_data = new FormData(this); //Creates new FormData object
                        $.ajax({
                            url : post_url,
                            type: request_method,
                            data : form_data,
                            contentType: false,
                            cache: false,
                            processData:false
                        }).done(function(response){ 
                            alert('Done');
                        });
                    });

                 
                    var id = this.getAttribute('id'); 
                    var novi = document.createElement('BUTTON'); 
                    novi.type = 'button'; 
                    
                    //alert("This object's ID attribute is set to \"" + id + "\".") 
                    novi.value = id; 
                    novi.innerHTML = 'x'; 
                    this.parentElement.replaceChild(novi,this); 
                    }; 
                 elem.innerHTML = elem.value; 
                 
                 docFrag.appendChild(elem); 
            } 
        document.body.appendChild(docFrag); 
        document.body.appendChild(row); 
    } 
</script>

Upvotes: 0

Views: 160

Answers (1)

minglyu
minglyu

Reputation: 3327

You need add X-requested-With header before you send the ajax request.

// you can omit  this if you use @csrf_exempt decorator in your views
data['csrfmiddlewaretoken'] = '{{ csrf_token }}';

$.ajax({
    type: "POST",
    // Django use X-requested-With header to identify Ajax
    beforeSend: function (xhr) {
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    },
    url: "{% url '<your_view_name>' %}",
    data: data,
    success: function (data) {
         console.log('success')
    }
});

In your views, then you can detect if the request is ajax simply using:

def your_view(request):
    if request.is_ajax() and request.POST:
        print(request.POST)
        # process the data

Take a look of the Docs for ajax

Upvotes: 1

Related Questions