views:

30

answers:

2

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"

}

}
A: 

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.

Nick Craver
I changed it like you sad with "books" but it also says that it is undifined.Also data.books.book1 returns undifined
Meko
@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.
Nick Craver
I edited what is result when alert(data)
Meko
@Meko - You're getting that exact *string* when you alert?
Nick Craver
yes.It returns this string
Meko
@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.
Nick Craver
I imported in index.html page where my form , <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> for jquery. Should I use for Json too?
Meko
@Meko - I meant a URL of a page demonstrating the problem above :) The JSON page should have *nothing* but the JSON in it coming back.
Nick Craver
site is on my local comp. not on internet.
Meko
@Meko - What does your output look like now?
Nick Craver
if I write alert(data) it shows [object Object] if I write alert(data.book1) it shows firstbook
Meko
A: 

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.

Meko