iva123
iva123

Reputation: 3515

Ajax post with Django and jquery

I'm new to all django, ajax things .. I read some tutorials on the net and I'm trying to make a simple form which posts some information via ajax.

Here is jquery part of my template :

<script type="text/javascript">

 $(document).ready(function () {

  $('#iEventAjax').submit( function()
  {
   var name = $('input[name=event_name]');
   var data = name.val();
   $.ajax({
                                type:"POST",
                                url:"/mediaplanner/edit/",
                                data:data,
                                success: function(msg){
                                        alert(msg);
                                }
                        });
  });

And the view code :

def iEventAjax(request):
        if request.is_ajax():
                return HttpResponse("ok")
        else:
                return render_to_response("iEventSave.html",{})

Well, when i post something, it returns iEventSave.html instead of giving the "ok" message. Any suggestions, which part do I fail ?

Upvotes: 0

Views: 1353

Answers (2)

David Miller
David Miller

Reputation: 2219

What is happening with this code:

  1. You bind a handler to the form on submit
  2. You then submit an ajax response which returns "ok"
  3. The form continues to submit as a regular HTML form
  4. The second submission returns the template because it is a GET request, not AJAX

In jQuery you need to either return false from the submit function, or call preventDefault on the event jQuery Submit Docs

So:

$(document).ready(function () {

$('#iEventAjax').submit( function()
{
 var name = $('input[name=event_name]');
 var data = name.val();
 $.ajax({
                            type:"POST",
                            url:"/mediaplanner/edit/",
                            data:{my_data:data},
                            success: function(msg){
                                    alert(msg);
                            }
                    });
return false;
});

Upvotes: 5

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You want to do var data = name.serialize(); to create a query-string parameter.

Upvotes: 0

Related Questions