The Python Oracle

Django Ajax Jquery Call

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Django Ajax Jquery Call
01:14 Answer 1 Score 0
02:01 Accepted Answer Score 12
02:44 Answer 3 Score 3
04:02 Thank you

--

Full question
https://stackoverflow.com/questions/1036...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#jquery #python #ajax #django

#avk47



ACCEPTED ANSWER

Score 12


I think the problem is at where you pass the data. Do you use Firebug? An excellent tool for checking if you pass anything in POST, it is an excellent tool for web development in general.

Here's a working example for sending Ajax call from a form

$("#form").submit(function(event) {
        var $form = $(this),
        $inputs = $form.find("input, select, button, textarea"),
        serializedData = $form.serialize();

        $.ajax({
            url: "/donate/",
            type: "post",
            data: serializeData,
            success: function(response) {
                alert(response)
            }
        })
        event.preventDefault();
    });

and then your view can look something like this

if request.is_ajax() or request.method == 'POST':
        form = DonateForm(data=request.POST)
        if form.is_valid():
            return HttpResponse("Success")
        else:
            return HttpResponse("Fail")

Btw, unless you really need all the extras from $.ajax() I would suggest you to use $.post() instead as it seems more straight forward to use.




ANSWER 2

Score 3


I think there are few things that are wrong with your code...

  1. You are sending a POST request to django without csrf_token => django will not return a success for this request. You need to send csrf_token with POST request. Check with firebug.

  2. Even if django is not giving any error then you are not changing the content of your page (on browser) anywhere... djang will send back this string -> "success" ...that's all.

You need to change your code like this,

add 'django.core.context_processors.csrf' to TEMPLATE_CONTEXT_PROCESSORS in settings.py to get access to csrf token in all templates.

your current template:

<html>
    <script type="text/javascript">
    $("#form").submit(function(e) {
        e.preventDefault();
        serializedData = $("#form").serialize();

        $.ajax({
           url: "/donate/",
           type: "post",
           data: serializeData,
           cache: 'false',
           dataType: "json",
           async: 'true',

           success: function(data) {
               alert(data)
           },
           error:function(data) {
               alert("error in getting from server")
           },
        });
    });  
    </script>
    <body>
        <form id="form">
            {% csrf_token %}
            {% for field in form %}
                {{ field }}
            {% endfor %}
        </form>
    <body>
</html>

donate view:

def donate(request):
    if request.method == 'POST':
        form = DonateForm(data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("SuccessFully Saved")
        else:
            return HttpResponse("Error in saving")

Now, you will see :

  • SuccessFully Saved -> if successfuly saved data.
  • Error in saving -> If data not saved for some reason.
  • error in getting from server -> if server responded with some error.



ANSWER 3

Score 0


The request.is_ajax() test checks whether the HTTP_X_REQUESTED_WITH header exists, which JQuery should be setting before it sends your request. (If you use XMLHttpRequest manually you have to add that header manually as well.) I personally like to go a different route because it's easier to test and doesn't rely on HTTP headers: adding a query parameter to the URL such as '?type=ajax'.

You'd then change request.is_ajax() to request.GET.get('type', null) == 'ajax' and in your JavaScript change url:"/donate/" to url:"/donate/?type=ajax".

The nice thing about this approach is you can test these calls without using AJAX just by adding that ?type=ajax string to any request.