Hick
Hick

Reputation: 36394

Jquery post not able to get any response from django views

This is my post script:

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

            $("#email").submit(function () {
                console.log("here2");
                var formData = $("#id_email").serialize();
                console.log("here1");
                $.post("http://127.0.0.1:8000/poste/", formData, function(result){
                    alert(result);
                    console.log("hi")}



            );            
            });
        });
    </script>

This is my django view:

@csrf_exempt
def posterous_view(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"
    print message
    return HttpResponse(message)

I want to print the message/response code at the front client script in an alert box, but according to my console, the function itself is not being called. Any reason why?

Upvotes: 0

Views: 182

Answers (1)

Bryan
Bryan

Reputation: 6752

You need to return false, so the form doesn't submit. If it DOES submit, then the ajax request will be terminated, and the form itself will take precedence. Try this out, and let's see if that's the issue :)

    $(document).ready(function () {

        $("#email").submit(function () {
            console.log("here2");
            var formData = $("#id_email").serialize();
            console.log("here1");
            $.post("/poste/", formData, function(result){
                alert(result);
                console.log("hi")
            });

            return false; // return false here
        });
    });

Upvotes: 2

Related Questions