views:

129

answers:

2

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)
+1  A: 

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

Ned Batchelder
Fixed that but still getting the same problem. Also happens if I put no mimetype and no datatype.
+4  A: 

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

Daniel Roseman
Thank you thank you - it all works now!