0

When I call json object from php file it returns undefined. I can see all data writing alert(data) but when I write alert(data.books) it returns undifined.

$JSON = '

{
  "books": {
 "book1": "firstbook",
 "book2": "secondbook"
  }
  }
';

and I call it with jquery

jQuery('#login').live('submit',function(event) {


$.ajax({
    url: 'lib/login.php',
    type: 'POST',
    dataType: 'json',
    data: $('#login').serialize(),
  success: function(data ) {

alert(' ' +data.books);

  if(data.books.book1){  
alert("OK"); 
}else
{
alert("error");   
}
}

 });

   return false;


});

EDIT This is how it returns alert(data)

    {

  "books": {

  "book1": "firstbook",

  "book2": "secondbook"

}

}
3
  • 1
    Don't you mean data.books.book1?
    – Pekka
    Sep 6, 2010 at 13:15
  • you are alerting data.success, not data.
    – aularon
    Sep 6, 2010 at 13:17
  • data.success, isn't defined according to your JSON format reply. Sep 6, 2010 at 13:19

2 Answers 2

0

If you're on jQuery 1.4+, the JSON you're returning isn't valid, it needs a set of quotes around the first books entry, like this:

{
  "books": {
    "book1": "firstbook",
    "book2": "secondbook"
  }
}

Earlier versions are more lenient about this, but once you correct it, alert(data.books) should result in an object alert. For your if(), you'd use data.books.book1 to get the entry in the JSON as it is now.

9
  • I changed it like you sad with "books" but it also says that it is undifined.Also data.books.book1 returns undifined
    – Ercan
    Sep 6, 2010 at 13:25
  • @Meko - If you do console.log(data), what are you seeing in the console? It sounds like your reply isn't formatted exactly like it is in the question. Sep 6, 2010 at 13:28
  • @Meko - You're getting that exact string when you alert? Sep 6, 2010 at 13:30
  • @Meko - Can you link to an example page? It's as if dataType: 'json' isn't even there, as it's seeing it as a string. Without headers saying it's JSON or the dataType, it'll be a normal string...that seems to be what's happening. Sep 6, 2010 at 13:36
  • I imported in index.html page where my form , <script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.4.1/…> for jquery. Should I use for Json too?
    – Ercan
    Sep 6, 2010 at 13:40
0

I changed in .php file like

$arr = array ( "book1" => "firstbook" ,"book2" => "secondbook" );

now it shows when i write alert(data.book1) out put fisrtbook .for checking if(data.book1) it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.