M
M
Mike2018-02-19 13:15:43
Django
Mike, 2018-02-19 13:15:43

How to get a message from the server using Ajax?

I don't know how to display "Hello World" message using framework messages along with Jquery and Ajax.
Without Jquery and Ajax, it turns out to display this message, but the page reloads, this is not good.
The user clicks on the link and, depending on the condition, either send him the link or display a message without reloading the page.
My two functions are in view and two templates.
views.py

from django.shortcuts import render, HttpResponseRedirect
from django.contrib import messages

def foo(request):
    print('I am foo')
    spam = 0
    if spam != 10:
        messages.info(request, 'Hellow world')
        return HttpResponseRedirect('/')
    return render(request, 'app/foo.html')

def index(request):
    return render(request, 'app/index.html')

index.html
<p>I'm index.html</p>
    <a href="{% url 'foo' %}" id="mylink">link</a>

foo.html
<p>I am link.html</p>
    {% for message in messages %}
        {{ message }}
    {% endfor %}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question