4

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?

function myPush(){
    $.getJSON("client.php?action=listen",function(d){
        d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
        $('#display').prepend(d.chat_msg+'<br />');
        if(d.failed != 'true'){ myPush(); }
    });
}

Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.

3 Answers 3

11

You don't need jQuery for this, just JavaScript. You can do it a few ways:

  • typeof d.failed- returns the type ('undefined', 'Number', etc)
  • d.hasOwnProperty('failed')- just in case it's inherited
  • 'failed' in d- check if it was ever set (even to undefined)

You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.

Reference:

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

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

Comments

1

Found this yesterday. CSS like selectors for JSON

http://jsonselect.org/

Comments

0

You can use a javascript idiom for if-statements like this:

if (d.failed) {
    // code in here will execute if not undefined or null
}

Simple as that. In your case it should be:

if (d.failed && d.failed != 'true') {
    myPush();
}

Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.

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.