Esrat
Esrat

Reputation: 99

Django: update a page without reloading

I want to update my homepage.html with button action and show some result from the server. But the problem is when I click on the button the whole page is reloading. Here, my project name is "T2KG". My form tag looks like this:

<form method="POST">
        {% csrf_token %}

        <center><textarea placeholder="Give a input sentence....."
      class="text" name="sent" rows="5" cols="70" font="15px arial, sans-serif" autofocus>Barack Obama born in Hawaii. Hawaii locates in USA.</textarea></center><br>
        <button type="submit" class="btn btn-primary btn-block" id="display_result">Generate Triple</button>
</form>

By searching in many websites I have understood that my view.py and urls.py is not correct and also I have to use AJAX. But How to implement in this situation I don't know. I have tried but couldn't find any way out. In view.py I return the value like this:

def result(request):
text = 'null'
if request.method == 'POST':
    form_input = Sentence(request.POST)
    if form_input.is_valid():
        text = form_input.cleaned_data['sent']
    else:
        form_input = Sentence()

triples = getTriples(text)

ent_list = entityList(text)
triples = predicateList(aggregate(triples, ent_list))
return render(request, './T2KG/homepage.html',{'triples': triples, 'json_triples': json.dumps(triples), 'text':text})

And my urls.py is:

urlpatterns = [
path('', views.set_sent, name='set_text'),
url(r'^T2KG/homepage', views.result, name='result'),]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Please help me.

Upvotes: 4

Views: 30179

Answers (3)

Ashish Singh
Ashish Singh

Reputation: 367

Ajax is used to send post data to views.py without reloading the page, also it does not affect your previously returned data.

Template

<script>
.
.
$.ajax({
    url : "url where you want to sent data"
    type : "POST", // http method
    data : {
      name:"name",
      csrfmiddlewaretoken: '{{ csrf_token }}' , //This is must for security in Django
    }, // data sent with the post request

    // handle a successful response
    success : function(response){
      alert(response["name"]);
    },

    // handle a non-successful response
    error : function() {
    .....
    }
});
.
.
</script>

views.py

def view_function(request):
    ..........
    if request.method == 'POST':
        name = 'change_name'
        return JsonResponse({"name":name})

Upvotes: 0

Ajax is created for resolving this issue, After first fresh reloaded page, All other updates and data from the server are fetch by ajax, If you want to develop a Dynamic web page you need to know Ajax

Upvotes: 0

Amandeep Singh
Amandeep Singh

Reputation: 315

What your looking is an ajax call to update the data on the page without the whole page refresh. For that, you would require a javascript call to send the form data to the backend and receive a json object back on success.

You can write a separate view for that or handle that by method check in the same view at python end(I prefer sep view for APIs). If using the same view remember to return the JSON object instead of a template renderer.

What javascript is doing is simply taking form data from your webpage and sending it to the designated URL then waiting for the response. For it to apply changes it needs a response(#can read about js promises). So there need to be a backend(python in this case) to listens to this call and return appropriate data(on success).

A nice follow links can be:

https://www.geeksforgeeks.org/handling-ajax-request-in-django/

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

http://www.tangowithdjango.com/book17/chapters/ajax.html

Upvotes: 8

Related Questions