Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a simple working ajax example for django forms

Basically I need something similar to http://www.w3schools.com/jquery/jquery_ajax_get_post.asp done in django. I've downloaded the samples and tested it locally with a localhost + php and it works out fine but I can't seem to get it to work in django no matter how simple the example is. Here's basically what I've done based on the example from the link above with slight modification

the javascript:

<script type="text/javascript">
$(document).ready(function(){
  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg"},
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function() { alert("error"); });
    return false;
  });
});
</script>

the urls:

url(r'^ajax/$', views.ajax_test, name="ajax"),

the views:

def ajax_test(request):
    if request.method == 'POST' and request.is_ajax():
        name = request.POST['name']
        city = request.POST['city']
        message = name + ' lives in ' + city

        return HttpResponse(json.dumps({'message': message})) #tried without the json. Doesn't work either

    return render(request, 'books/ajaxTest.html')

the html:

<form id="my_form" action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>{% csrf_token %}
<input type="submit" value="Send">
</form>

The form is suppose to include a django form but since I can't even get the basics to work, that would be kinda pointless. Someone mentioned about the csrf_token tag but removing that doesn't solve the problem either. The output of the above example basically just yields the alert('error') and nothing else. I've been through so many examples but I can't even get the most basic ones to work

like image 454
Allan Eswar Avatar asked May 29 '13 12:05

Allan Eswar


People also ask

Can you use AJAX with django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.

How send data from AJAX to django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

What is AJAX explain with example?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


1 Answers

OK..thx for your comments..I got it all sorted out..basically I just missed out on the {% csrf_token %} and csrfmiddlewaretoken:'{{ csrf_token }}'..just for the benefit of those who might be reading this..the new codes will look something like this

the javascript:

<script type="text/javascript">
$(document).ready(function(){

  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg",
     csrfmiddlewaretoken:'{{ csrf_token }}'
     },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function(xhr) {
        console.log("Error: " + xhr.statusText);
        alert("Error: " + xhr.statusText);
    });
    return false;
  });

});
</script>

the html:

<form id="my_form" action="" method="post">{% csrf_token %}
<input type="submit" value="Send">
</form>
like image 89
Allan Eswar Avatar answered Oct 01 '22 20:10

Allan Eswar