0

I have a PHP script that outputs a JSON associative array when an ajax call is made to it. The first key and value in the array (["status" : "failed"]) shows the status. The second key and value (["message" : "Invalid Input"]) shows the message. So i need to first run a check whether the status is "failed", if it is, get the corresponding error message and vice versa.

The problem is how do I get the second key and value pair to get the message.

Here's the JavaScript I'm utilizing:

            var frmdata = new FormData($('#order-form')[0]);        
            $.ajax({
                type: "POST",
                dataType: "json",
                url: 'classes/validate.php',
                cache: false,
                contentType: false,
                processData: false,   
                data: frmdata,
                success: function(data) {
                    $.each( data, function( key, value ) {
                        if (key == "status") {
                            if (value == "failed") {

                            } else if (value == "success") {

                            }
                        }
                    });
                }
            }); 

Here's the PHP script;

    public function outputJSON($status, $message)
    {
        $this->json_output["status"] = $status;
        $this->json_output["message"] = $message;
        $json = json_encode($this->json_output, true);
        return $json;
    }
8
  • Can you console.log(data)? Commented Sep 27, 2015 at 3:29
  • How about having response object as {status:'failed',message:'Invlaid Input'}. You can read it like data.status Commented Sep 27, 2015 at 3:30
  • @aldrin27 Object {status: "failed", message: "Invalid service selected"} Commented Sep 27, 2015 at 3:35
  • 2
    Try: if(data.status == 'failed') { alert(data.message); }else { data.message} Commented Sep 27, 2015 at 3:38
  • 1
    See what is JSON, how to use the JSON object, and how it differs from the JavaScript objects. Commented Sep 27, 2015 at 3:39

1 Answer 1

1

Try this:

public function outputJSON($status, $message) {
  $json = json_encode(array('status'=>$status,'message'=>$message));
  return $json;
}
var frmdata = new FormData($('#order-form')[0]);
$.ajax({
  type: "POST",
  dataType: "json",
  url: 'classes/validate.php',
  cache: false,
  contentType: false,
  processData: false,
  data: frmdata,
  success: function(data) {
    if (data.status === 'failed') {
      alert(data.message);
    } else {
      //data.status is success
    }
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I needed.

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.