How to validate value that comes by json from php to ajax

Asked

Viewed 66 times

0

In php I have the following return:

            $invalido = (object) array(
                'invalido' => true
            );
            echo json_encode($invalido);

and I need to show on success of ajax asked if the invalido is true. I tried the following:

success: function(data) {
            //alert(data);

           if(data.invalido == true)
           {
               alert('invalido');
           }

        }

It is not entering the if, and the top Alert is displaying the following:

{"invalido":true}{"scalar":false}

How valid what’s coming in invalido?

I need to access what’s coming in this json, access the invalido:

{"invalido":true}{"scalar":false}

1 answer

0

Try

var data = [{
  "invalido": true
}, {
  "scalar": false
}];

if (data[0].invalido == true) {
  console.log('invalido');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or

var data = [{
  "invalido": true
}, {
  "scalar": false
}];


$.each(data, function(key, value) {
  if (value.invalido == true)
    console.log("invalido");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Thank you. I am already receiving a json and need only validate the invalido of this json.

  • @SM_S put two ways in how you can access the invalid key value and make its due validations.

  • Is showing this error by the second way: Cannot use 'in' operator to search for 'length' in {"invalido":true}{"scalar":false}

  • Any more suggestions?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.