2

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.

3
  • You don't need to provide such a response - it is implicit in 200 OK HTTP response code :)) - different matter if you want to provide a richer or localised message, but still matter of discussion [I wouldn't either]. Commented Apr 18, 2013 at 9:14
  • FYI, {success: true} is invalid JSON. Keys must be strings! Commented Apr 18, 2013 at 9:17
  • @FelixKling - Chrome dev tools Network panel shows it as {success:true} but the 'actual' server sends {'success':true} but thanks for letting me know that! :) Commented Apr 18, 2013 at 9:22

3 Answers 3

7

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() {

    }
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

Status code is 200, that's an interesting way to do it. However, the other answer below worked nicely :)!
The idaea is, if your request is wrong (invalid fields or something), the whole request fails. You can then use the whole body to describe the error and it will fall through to the error field in your javascript (ajax) command. Switch on the error codes. The result is that your success stays nice and clean to only do stuff when your request is ok.
Thanks Ferdy, that sounds a more progressive way. Do you have any code snippets on how I could do this?
What language is your backend?
1

The following should work:

success: function(result) {
  var thing = $.parseJSON(result.d);
  if (thing.success) {

  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.