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.
My Answer:
To access PHP session data inside template files in jQuery code, you can pass the session data as a parameter in your AJAX call to the PHP file. Here's an example:
1. In your template file (e.g. index.php), you can store the session data in a JavaScript variable like this:
html
2. In your jQuery AJAX call, you can pass the session data as a parameter like this:
javascript
$.ajax({
url: 'your_php_file.php',
type: 'POST',
data: {
sessionData: sessionData
},
success: function(response) {
// Handle the response from the PHP file
}
});
3. In your PHP file (your_php_file.php), you can access the session data like this:
php
session_start();
if(isset($_POST['sessionData'])) {
$sessionData = $_POST['sessionData'];
// Use the session data as needed
}
By passing the session data as a parameter in your AJAX call, you can access the PHP session data inside your template files in jQuery code.
Rate this post
5 of 5 based on 1076 votesComments