views:

66

answers:

1

i want to make an ajax call to a php file that return a users info in json then take that data and put it in an object property

example:

System = {
 prop1= ''
}

i just want to override the prop1 property

im using jquery to make the ajax call

A: 

The easiest way to set up JSON output in PHP is to simply use a stdClass() object and call json_encode() on it.

$obj = new stdClass();
$obj->name = 'user name';
$obj->prop1 = 'property 1';

echo json_encode($obj);

After you receive this from the Ajax call, you'll have a javascript object with a name and a prop1 property.

If you want to replace an existing object's properties with the ones you fetched from your Ajax call, you'll have to do it manually, ie. check the JSON result for the property you want, and set it on your existing object. The way around that would be to only output the properties you want in your JSON, and just use them all by iterating over the fetched ajax object. Example:

for(prop in fetchedAjaxObject) {
    existingObject.prop = x.prop;
}

EDIT

In response to your comment below, it sounds like you just want to get the JSON object from the result of a JQuery call?

In that case you just set up a handler function for the "success" property of the ajax call. The result automatically gets passed to the handler function. There's examples in the JQuery docs, but here's a basic one:

$.ajax({
    url: 'www.example.com',
    success: function(data) {
        //data is your JSON object
        yourObject.prop = data.prop1;
    }
});
zombat
im sorry i should have put that i already have the data from the php file im just trying to figure out how to get it out of the callback from jquery.
theunilife
Don't forget `dataType:"json"`, or better, just use `getJSON`.
Crescent Fresh
here is what my current code looks like but it doesnt work it makes the property fname in to a local variable only to be used in side the callbackSystem.User = { fname: 'null', avatar: typeof(avatar) != 'undefined' ? this.avatar : 'user.ico', setInfo: function(name){ name = typeof(name) != 'undefined' ? name : System.User.username; $.post('lib/system.userinfo.php', {name: name}, function(data){ System.User.fname = data.fname; },'json'); }}
theunilife