0

Well, sorry for my bad grammar, but any help will be much appreciated..

Ok, here I'm trying to encode string by using json inside PHP then using JavaScript to read the json string. It will have 2 cases here. The first one is, the application will running normally, so does the encode. The json string will be like this :

{"employee":
[{"id":"1","firstName":"aaa","lastName":"abc","timeIn":"08:00:00","timeOut":"17:00:00"},
{"id":"2","firstName":"bbb","lastName":"def","timeIn":"08:00:00","timeOut":"16:45:00"}]}

and the second one is, the PHP can't read the MySQL database, so in PHP the json encode will be like this :

{"errorProcess":{"text":SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. }}

The question is, in JavaScript how can I make an IF statement in JavaScript based on the result string in json? Maybe it will be like this, but I don't know how to write it in JavaScript.

IF (in json string has employee){then result}
else if(in json string has errorProcess){then result}

Thanks for your help

1
  • 1
    How are you parsing json in javascript? You need to turn it into a javascript object first Commented Dec 28, 2013 at 20:20

3 Answers 3

3

You can check for errorProcess key using

if(json.hasOwnProperty('errorProcess')){
   //do struff
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was gonna write an answer with typeof json.errorProcess != 'undefined' but this seems way more elegant
1

JSON keys and values are accessed using dot (.) notation in Javascript. Assuming you already have the JSON as an object (not a string), you can simply write

if (json.employee) {
  // do something
}
else if (json.error) {
  // do something else
}

where json is a variable referencing your returned JSON from the php.

If your JSON is still in string format, you need to parse it into an object. This can be done with the built in JSON object.

var json = JSON.parse(jsonAsString);

Comments

1

First you need to parese JSON like this

var jsonObject= jQuery.parseJSON(yourJsonObj);

if(jsonObject.hasOwnProperty('employee')){
// Add your code

}else if(jsonObject.hasOwnProperty('errorProcess')){
// Add your code
}

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.