> when I just use data it shows the JSON encoded data
 
That's your problem right there. Your data variable should not be "JSON
encoded data" (which is a string). It should be the actual JavaScript
object.
 
Try console.log( typeof data ) to see what I'm talking about.
 
Why are you getting a string instead of a JavaScript object?
 
            datatype:'json', //Return JSON encoded data

Take another look at the docs for the $.ajax options, keeping in mind that
JavaScript is case dependent. Also note that the comment is misleading:
encoded data is what you don't want. (Ironically, because of the misspelled
option name, it is what you're getting.) You want decoded data:
 
            dataType:'json', // Decode JSON response into JavaScript data

-Mike



  _____  

From: jquery-en@googlegroups.com [mailto:jquery...@googlegroups.com] On
Behalf Of Joey Derrico
Sent: Tuesday, August 11, 2009 12:17 PM
To: jquery-en@googlegroups.com
Subject: [jQuery] Re: AJAX and JSON


Ok so I have used .ajax function to run my ajax and set type to data. It is
getting (well posting) to a php file that echo's a json_encoded array. When
it returns I am using console.log to display the returned data. when I just
use data it shows the JSON encoded data, but if I use data.key I get
undefined. How can I get it to show me the data from the JSON variable? 

Here is the script
        $.ajax({ //Begin ajax statement to login file
            type:'POST', //It is a Post request
            url:'functions/php/login.php', //The login file
            datatype:'json', //Return JSON encoded data
            data:{ //Data being sent to the server is...
                Username:$('#CharacterBuilderUsername').val(), //Username
                Password:$('#CharacterBuilderPassword').val() //Password
            },
            cache:false, //Don't Cache the file
            success:function(data){ //if successful....
                $('#UserBar').load('main_pages/UserBar.php'); //Run an AJAX
request for the user menu
                console.log("Data: "+data); //Shows Json data: Data:
{"PlayerId":1,"PlayerName":"First Last"}
                console.log("PlayerId: "+data.PlayerId); //Shows undefined
                console.log("Player's Name: "+data.PlayerName); //Shows
Undefined
                var testdata=data.PlayerId;
                console.log("Returned Data="+testdata); //shows undefined
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){ //if
not successful...
                $('#CharacterBuilderLoginSubmit').show(0); //show the submit
button
            },
        });
    });

>From the PHP file, not the whole script
        $UserInfo['PlayerId']=$PlayerId;
        $UserInfo['PlayerName']=$PlayerFirstName." ".$PlayerLastName;
        echo json_encode($UserInfo);


Reply via email to