alexx0186
alexx0186

Reputation: 1557

in Jquery, how can I alert one part of a JSON object? I get "undefined"

I have a an array:

$result = array('statusAlert' => 'Your input was validated'
                 'input' => $input); // $input is a string

json_encode($result);

in jQuery, I want to alert 'statusAlert' and 'input' separately? How do I access them?

I tried alert(result.statusAlert), alert(result[0]), alert(result.statusAlert[0]) but none of them has worked.

Edit

I am trying to do that within the "success" callback function of ajax() in jQuery

When I alert(result), I get:

{"statusAlert":"Your input was validated","input":"this is the string input"}

Upvotes: 1

Views: 94

Answers (3)

Shyju
Shyju

Reputation: 218762

If you have a valid json like this

'{"statusAlert":"Your input was validated","input":"this is the string input"}'

You can get the values like this

jsonObj.statusAlert

jsonObj.input

Here is the sample http://jsfiddle.net/kfrTz/8/

You can use http://jsonlint.com/ to verify your jSon is in correct form or not.

Specifying json as the data type value in your ajax request will make sure the reponse is coming back as json format to the success callback.

$.ajax({
   url:"yourserverpage.php",
   datatype='json',
   success: function(data) {
      alert(data.statusAlert);
   }

 });

Upvotes: 1

user1106925
user1106925

Reputation:

Change your .ajax() request to include dataType:'json'.

Upvotes: 1

Death
Death

Reputation: 2017

Did you specify dataType: 'json' in your $.ajax parameters?

Presuming you have and you've used the jQuery $.getJSON or $.ajax functions and it's still not working, then your result should be an array, not an object, as you created it in PHP as an array. You'll be looking to read it as:

alert(result['statusAlert']);

and

alert(result['input']);

Upvotes: 1

Related Questions