Huy Than
Huy Than

Reputation: 1546

Ajax POST and GET in django

I am learning how to use Ajax GET and POST in Django, I have this problem, please spare your time to help me.Thanks!

The problem I have is that when I click on POST button, it always goes to the views.ajax_get (when I expect it should go to views.ajax_post).

Here is the HTML template

<button class="get_button" id="get-button" type="button">Get button</button>

<form method="POST">
  {%csrf_token%}
  <button class="post_button" id="post-button" type="submit">Post button</button>
</form>

Here is the Javascripts:

<script>
  $(document).ready(function() {
    $('.get_button').click(function() {

  $.ajax({
    type: "GET",
    url: "{%url 'myapp:ajax_get' %}",
    success: function(response) {
      alert('Ajax GET')
    }
  });
});

$('.post_button').click(function() {

  $.ajax({
    type: "POST",
    url: "{%url 'myapp:ajax_post' %}",
    success: function(response) {
      alert('Ajax POST');
    }
  });
});

// CSRF code
function getCookie(name) {
  var cookieValue = null;
  var i = 0;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (i; 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;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
    $.ajaxSetup({
      crossDomain: false, // obviates need for sameOrigin test
      beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });

  });
</script>

Upvotes: 0

Views: 76

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You haven't disabled the default action of the form or button. So the Ajax is triggered, but then the form is submitted via the browser normally.

Upvotes: 1

Related Questions