N
N
NikClik2018-08-19 19:39:53
Django
NikClik, 2018-08-19 19:39:53

How to get data from a template on button click without reloading the page?

I need to send data (which is placed in the input on the template) to the def by clicking on the button, but the page cannot be reloaded, i.e. it is impossible to transfer data through the form on the template or by accessing the url when the button is clicked, because they will reload the page, whereas how can this be done without reloading the page?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aleksey Solovyev, 2018-08-19
@NikClik

For form submit Event.preventDefault();
After we send AJAX request:

// this is the id of the form
$("#idForm").submit(function(e) {


    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the django.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

Plain JS: XMLHttpRequest
var http = new XMLHttpRequest();
http.open('POST', url, true);
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        console.log(http.responseText);
    }
}
http.send(params);

JQ Ajax
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

S
Socrates, 2018-08-19
@Karmov69

vue in conjunction if it is convenient to use I think very

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question