PhoebeB
PhoebeB

Reputation: 8570

How to get django and jquery .ajax to play nice - not triggering success

At this all evening and can't see what I'm missing:

JS:

$(document).ready(function() {

    $("#form").submit(function () {

        var txt = $('textarea[name=text]').val();  

        $.ajax({  
          type: "POST",  
          url: "/parse_text/",
          data: {"text": txt},  
          dataType: "text",
          success: function(h) {  
            alert('ok');
          },
          error: function() {  
            alert('failed');
          }  
        }); 

    });
});

And the django code:

def parse_text(request):


    return HttpResponse("hello", mimetype="text'/plain")

I can't get it to trigger the success method. Using firebug I can see that django is return "hello" and a status of 200.

I also tried changing to json (though what I really want is to return an html table).

In js:

dataType: "json",

In view:

return HttpResponse('[{"hello": "hello"}]', mimetype="application'/json")

Now return [{"hello": "hello"}] and 200 status.

What on earth am I doing wrong!?

Final working code:

$(document).ready(function() {

    $("#form").submit(function () {

        var txt = $('textarea[name=text]').val();  

        $.ajax({  
          type: "POST",  
          url: "/parse_text/",
          data: {text : txt},
          success: function(html) {  
            $("#actions").html(html);
          },
          error: function() {  
            alert("fail");
          }  
        }); 
        return false;
    });
});

and in the view:

def parse_text(request):

    html = ''
    text = request.POST['text']

    ... generated some html based on the text ...


    return HttpResponse(html)

Upvotes: 0

Views: 1275

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599550

Your jQuery function doesn't prevent the form submit from taking place. So, since Ajax is asynchronous, the submit happens before the data is returned from the Ajax request, and the function never sees it.

To fix this, make sure you have return false; at the end of the submit function - ie before the second-from-last }) .

Upvotes: 5

Ned Batchelder
Ned Batchelder

Reputation: 375574

Both of your examples of mimetype include an extra apostrophe: mimetype="text'/plain". Is that the way the code really is?

Upvotes: 1

Related Questions