Skip to content
Advertisement

How use vanilla JavaScript to add ajax request on Django instead of Jquery

All tutorials cover the implementation of AJAX in Django only using the JQuery library.

$.ajax({
    url: form.attr("data-validate-username-url"),
    data: form.serialize(),
    dataType: 'json',
    success: function (data) {
      if (data.is_taken) {
        alert(data.error_message);
      }
    }
  });

But I want to use the vanilla JavaScript to handle everything, anyway to do that?

Advertisement

Answer

Actually, you can read the documentation of the Fetch API and translate the JQuery part into the Fetch API.

Anyway, here is how it works: To go with vanilla JavaScript and make an AJAX GET request using the Fetch API, we have three or maybe four steps.

fetch('url')
.then(response =>{return response.json()})
.then(data => {//take care of the data you got})
.catch(error => {//handle the error})

We are using here the fetch to make a GET request from the url we are fetching. Once the response is completed, we got a response, to read that response, we convert it into json format or it could be text format or whatever you want. For that we create another .then handler that have access to our json object.

Now how to use that in Django?

I will assume that you have this view that will handle the ajax request:

def ajax_get_request(request):
    data  = {"message":"a message to send to the tempalte"}
    return JsonResponse(data)

and let’s say you specified this urlpattern for that view:

...
path("ajax-get/", views.ajax_get_view, name="ajax"),
...

Now, simply in your tempalte, here is how to handle that request:

<script>
fetch("{% url 'ajax' %}")
.then(response => {
    return response.json();
})
.then(data =>{
   console.log(data.message);
}
</script>

For the POST request, things might be quite different, I recommend reading this article, it covers the how to handle AJAX POST request in Django with the Fetch API.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement