0

In the simple code snippet below, i am getting a JSON response from a php page and then trying to iterate it and alert out the name field on each JSON objects. But it doesnt alert out anything.

<html>
<head>
  <title>AJAX DB</title>
</head>

<body>

  Name: <input type="text" id="name">
  <input type="submit" id="name-submit">
  <div id="formatted-data"></div>
  <div id="name-data"></div>

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script >

  $('input#name-submit').on('click',function(){
    var name = $('input#name').val();

    if($.trim(name) != ''){
      $.post('appservice.php', {search_key: 'users_search', search_value:  name}, function(data){
        //$('div#name-data').text(search_data);
        $.each(data, function(i, obj) {
          alert(obj.name);
        });
      });
    }
  });

  </script>
</body>
</html>

sample JSON

[
  {
    "id": 18927441,
    "id_str": "18927441",
    "name": "IGN",
    "screen_name": "IGN",
    "location": "San Francisco, CA"
  }
]
4
  • If you console.log(data), is it a string or an object? If it's a string, then you need to use data = JSON.parse(data); to convert it from json to object first. Commented Nov 8, 2015 at 9:06
  • Thanks a lot! cant believe i was missing such a basic point. Can you explain why is it like that though? I was just copy pasting the response in an online JSON parser and it detected the echoed out string as valid JSON. So i thought it was already a JSON object. Commented Nov 8, 2015 at 9:12
  • 1
    Because you didn't pass dataType to .post, so jquery guess it based on return object, which would based on the return info from your php, and it seems jquery guess it's text, so it didn't parse it for you, instead it gives you the raw content. Things would change if you pass json as 4th param. Commented Nov 8, 2015 at 9:15
  • makes sense, thanks! Commented Nov 8, 2015 at 9:18

1 Answer 1

1

You can't utilize JSON while it is still in JSON string form. You need to parse it to use it. Try:

data = JSON.parse(data);
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.