views:

113

answers:

3

Hi i've got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this

function func_load_session(svar){

var id = '';

$.getJSON('data/session.php?load='+svar, function(json){

  eval('id = json.'+svar);

});

return id;

}

this code i load session from php file that i've store beforehand. i store that session variable using dynamic var.

<?php
/*
* format ?var=[nama_var]&val=[nilai_nama_var]
*/ 

$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'";
}else if($load){
  echo $_SESSION["$load"];  
}
?>

using firebug, i get expected response but i also received error

uncaught exception: Syntax error, unrecognized expression: )

pointing at this

eval('id = json.'+svar);

i wonder how to solve this

+3  A: 

The correct code to use is:

id = json[svar];

You may also want to add alert(svar); to check that svar contains the correct value beforehand.

However, your code still won't work: the func_load_session function will return immediately, before the ajax call finishes and before the id variable is assigned.

what you need to do instead is to perform whatever you want to do with id from the ajax callback function:

function func_load_session(svar){
    $.getJSON('data/session.php?load='+svar, function(json){
        var id = json[svar];
        doSomethingWith(id);
    });
}
interjay
+1  A: 

Also If I understand and have full part of your code Your json comes out like Store["var"]="var" ?? Does not appear valid json

I suggest using php function json_encode()

So php would be

 $var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo json_encode(array($var=>$_SESSION[$var])); // or something like that 
}else if($load){
  echo json_encode(array('load'=>$_SESSION["$load"]);  
}
?>
Shaun Hare
A: 

thanks interjay to teach me that, i've edited it as you refer to.

eval('id = json.'+svar); to id = json[svar];

but i still have that error statement. i've edited it as you refer to. but i think its weird, i got expected result but i still receive that error.

Miftah
PLease provide your json output from the php
Shaun Hare
In the future, to respond to someone's answer, press `add comment` below their answer, or they may not see your response. Anyway, shaunhare is also correct in that your PHP doesn't seem to be outputting json and you probably need to call json_encode.
interjay
please provide the json Output, cause depending on how the array is formatted, json return data, so you may need to eval() in dirrent way!
aSeptik
thanks all i'll try it my best. sorry for my poor manner
Miftah