I've using jQuery on my contact form for a web app we're building, I am getting a JSON response from the server which is:
{"success": true}
Here's my jQuery so far:
$('.contact-form').on('submit', function(e) {
// Prevent submitting
e.preventDefault();
// Loading from data-* attr
var $submit = $('#contact-submit');
$submit.html($submit.data('text'));
// Form data
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
// Ajax call
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
dataType: 'json',
success: function(){
},
error: function(){
}
});
});
I've hit a wall as I've never 'checked' against a JSON response before in the 'success' jQuery method, can anyone help on this? I am looking for a method of checking the response I'm getting, and if 'true' is presented, I will then show a 'Sent success' message.
The success callback will get the json object as the first parameter, you can use it in the callback as shown below
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
dataType : 'json',
success : function(data) {
if(data.success){
//do something if success
}
},
error : function() {
}
});
Why not reply the server with forexample HTTP code 200 (OK) or 201 (Created). Then in jQuery automatically fall in the success parameter is where everything went ok.
When server has a error, use for example code 422 (Unprocessable Entity), then jQuery ajax will automatically fall in error.
If this is impossible, just try and parse using JSON.parse(data) and walk down the tree. If parse fails, json is invalid.
Asuming Java Backend, your reply would look something like described here: How to send a HTTP error for a Java RESTful web service?; This is really depending on what classes / frameworks you are using. Set the HttpReponse status to 422 for example.
Your ajax call would look something like:
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
dataType: 'json',
success: function(){
// Everything went okay
},
statusCode: {
422: function() {
// Something went wrong (error in data serverside)
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With