Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate json member using variable ?

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

like image 555
Miftah Avatar asked Apr 06 '26 10:04

Miftah


1 Answers

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);
    });
}
like image 63
interjay Avatar answered Apr 09 '26 00:04

interjay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!