I have ajax that calls a php file called "fetch_quarter_limit.php" from template file.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
var quarter_limit = data['myVar'];
alert(quarter_limit);
}
});
In my .php file i have tried to return the session data as an array. Fetched the required data, stored in session and formed an array.
$_SESSION['quarter_limit_mend'] = $quarterLimit;
$returnVal = array('myVar' => $_SESSION['quarter_limit_mend']);
echo $returnVal;
As shown in above ajax code part, i tried to fetch it, but all i am getting is "undefined" when i output the variable using alert.
Please help.
Ajax code updated, p2 :
Adding dataType is making code not to work.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
dataType: 'json',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
alert(data);
}
});
As @Tim mentioned i have added custom json encode function to my .php file. It returns as expected {"myVar": 2}
echo array_to_json($returnVal);
This is returned from php file. But not able to access in ajax code.
php version in < 5...then you need to upgrade urgently. You are years out of support. php.net/supported-versions.php . I guess you'll have to make the JSON manually then, or find a polyfill. Echoing an array directly in PHP will just produce a warning (or nothing, if warnings are switched off, or set to log to a file) because it can't directly convert an array to a string (and even if it could, it still wouldn't be valid JSON that Javascript could read).