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 ?

Answers


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;
});

Need Your Help

Read date from file name

c# wpf datetime

What I need to do is to convert a string that I obtain reading a file's name, in the form of yyyyMMdd.log and transform it in an object of type 'DateTime'.

Possible to add auto incrementing variable to row results of GROUP BY in mysql?

mysql

Basically, I'm using this query to group a bunch of users based on the sum of numbers associated with them. I need to some how assign an index to each result. I am blanking on how to do this. I'm