user94628
user94628

Reputation: 3721

Tornado doesn't send Ajax response to client

Upon form submit the Tornado server does some checks and sends a response back to the client, which should appear in that current page as an alert.

Instead a blank html page is rendered with the Json response, but not as an alert on the current page where the form was submitted.

On submit the form is sent via post to /dh (DataHandler)

This is the Jquery:

$.post("/dh",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
    },"json");

The Tornado code:

class DataHandler(BaseHandler): 
    def post(self):

        # Checks are done with form data received

        dupInfo={
            'tel' : duptel,
            'name' : dupName
             }

        self.write(json.dumps(dupInfo, default=json_util.default))
        self.finish()

So how can you return this json to the current page?

Upvotes: 2

Views: 735

Answers (2)

Cabrera
Cabrera

Reputation: 1960

Give your form an id and stop the default redirect after submission:

$("#yourForm").submit(function (event) {
    event.preventDefault();

    jQuery.ajax({
        url: "/dh",
        data: {
        // whatever data you are passing to handler
        },
        dataType: "json",
        type: "POST"
    }).done(function (data, textStatus, jqXHR) {
       // call was successful
       // access response data
       alert(data['tel'])
       alert(data['name'])
    }).fail(function (jqXHR, textStatus, errorThrown) {
       // call error
       // access response data
       var data = jqXHR.responseJSON;
       alert(data['tel'])
       alert(data['name'])
    });
});

Based on your handler, you should end up in the done callback rather than the fail one.

Upvotes: 0

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

After the "alert" statement, add return false;. This disables the browser's default handling of the POST event. The browser's default behavior is to navigate to the new URL, and you want to prevent that.

Upvotes: 3

Related Questions