Sergei Petrov
Sergei Petrov

Reputation: 93

Updating info on html page using Ajax in Django

I have a problem with Ajax and how can I update info on my HTML page without reloading it.
So, I have a function in my views.py file:

def index(request):
  some stuff
  context = {
      some stuff
  }
  return render(request, "header.html", context)

And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it?

Upvotes: 2

Views: 1566

Answers (1)

Sachin
Sachin

Reputation: 3674

First, create a new endpoint to get the desired data in whichever format. I prefer JSON.

New endpoint:

# views.py

from django.http import JsonResponse
def new_endpoint(request):
    """Returns `JsonResponse` object"""

    # you can change the request method in the following condition.
    # I dont know what you're dealing with.
    if request.is_ajax() and request.method == 'GET':
        # main logic here setting the value of resp_data

        resp_data = {
            'html': 'stuff',
            # more data
        }

        return JsonResponse(resp_data, status=200)

Then, you need to code the AJAX part calling this endpoint with the method, data, headers, etc. and finally, define the success callback method to get the desired data.

AJAX:

var data = {};
$.ajax({
  url: '/your-new-endpoint-url',
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(resp) {
    $('#changingElement').html(resp.html);
  }
});

You can send any type of data from this new endpoint to change whatever element's html text or class name or styles, etc.

Upvotes: 6

Related Questions