0

I'm attempting to retrieve json output from a php file and output a value. Can someone enlighten me on how to detect if the value is undefined and how to access one of the values in the array?

php response:
{"myObj":[{"userid":"9000","name":"Foo"},{"userid":"1000","name":"Bar"}]}

$.ajax({
    type: 'POST',
    url: 'reply.php',
    beforeSend: function (xhr) {
        if (xhr && xhr.overrideMimeType) {
            xhr.overrideMimeType('application/json;charset=utf-8');
        }
    },
    data: {
        "action": "getmyObj"
    },
    success: function (reply) {
    if (reply.myObj.length > 0) {
        for (i = 0; i < 3; i++){
            if (typeof reply.myObj[i].name === 'undefined') {
                console.log("Undefined");
            } else {
                alert(reply.myObj[i].name);
        }
    }
});
1
  • what error you are facing? you code seems correct Commented Jul 5, 2021 at 21:21

1 Answer 1

1

you could replace

for (i = 0; i < 3; i++){

with

for (i = 0; i < reply.myObj.length; i++){

this way it will iterate according to how many entries there are instead of static 3 times, then u probably won´t even have to check if prop is undefined (because it is for the third iteration)

the check for the property though should be as simple as:

if (!reply.myObj[i].name) {
    console.log("Undefined");
} else {
    alert(reply.myObj[i].name);

because of the mentioned above u can be sure that reply.myObj[i] is defined

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

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.