Reputation: 2587
I am having some problems with making jQuery work on GAE python 2.7 . The main problem is jQuery cant catch the json data returned by the server.
A simple comment form with nothing special:
<form action="/postcomment/" method="post" id="commentform">
<input type="text" name="author" id="author" onfocus="if(this.value=='Name: (required)') this.value='';" onblur="if(this.value=='') this.value='Name: (required)';" {% if name %}value="{{ name }}"{% else %}value="Name: (required)"{% endif %} size="22" tabindex="1" aria-required='true' />
<input type="text" name="email" id="email" onfocus="if(this.value=='E-Mail: (required)') this.value='';" onblur="if(this.value=='') this.value='E-Mail: (required)';" {% if email %}value="{{ email }}"{% else %}value="E-Mail: (required)"{% endif %} size="22" tabindex="2" aria-required='true' />
<textarea name="comment" id="comment" cols="100%" rows="10" tabindex="3"></textarea>
<input name="submit" type="submit" id="submit" tabindex="4" value="Submit" />
</form>
My jQuery code (only structure to make it simpler):
$("#submit").click(function() {
$.ajax({
dataType: 'json',
beforeSubmit: function() {
},
timeout: 60000,
error: function(request,error) {
},
success: function(data) {
var obj = jQuery.parseJSON(data);
//blah blah...
} // End success
}); // End ajax method
});
On the server side:
class PostComment(BaseHandler):
def post(self):
self.response.headers['Content-Type'] = "application/json"
response = {'errorcode': 0}
self.response.out.write(json.dumps(response))
The result is: After I click the "submit" button, My Firefox 3.6 browser says: There is "application/json" file, do you want to open it with which tool?
I was expecting jQuery to catch this 'json' data and process it. But it didnt happen.
I believe I am almost there but something is wrong.
Upvotes: 0
Views: 504
Reputation: 1124558
You need to cancel the default action of the form, which is to submit (which cancels any running JavaScript AJAX query in progress):
$("#submit").click(function() {
$.ajax({
dataType: 'json',
beforeSubmit: function() {
},
timeout: 60000,
error: function(request,error) {
},
success: function(data) {
var obj = jQuery.parseJSON(data);
//blah blah...
} // End success
}); // End ajax method
return false; // Cancel default action.
});
By returning false
from the click handler, the normal form action, which is for the browser to submit the data to the URL named in the action
attribute, is not executed.
Upvotes: 2