Making Json objects using Session Variables in another file - javascript

I was trying to make a Json Object of some variables Which I am using as Session variables, But I am not geting the proper Response To make it as Json Object ..
Some Code which I tried (for Reference) Sharing Below..
//Passing the Variable To another PHP File
session_start();
$_SESSION['EmailIds']=$strEmailIds;
$_SESSION['SCHOOL_NAME']=$SCHOOL_NAME;
//sending data to another php page ..
header('Location: ../SecondPage.php');
In second file SecondPage.php Where i was Using This Session..
session_start();
$SCHOOL_NAME = $_SESSION['SCHOOL_NAME'];//1
$EmailIds= $_SESSION['EmailIds'];//1 <br>
Now trying to make this Session Variable in Json OBject...????
var OBJ = jsonObj.(SCHOOL_NAME+EmailIds);// Confuse with THis Line<br>
Actuaaly Not Getting What is the Good Approach To make this variables as Json Objects..
AS I Made this Json Object I can Use This AS another Purpose Like to send as Ajax Data and etc..

You can use json_encode method like this :
$someArray; //can be array of your values or $_SESSION
$jsonObj = json_encode($someArray);

get session data in an array like :
$data['SCHOOL_NAME'] = $_SESSION['SCHOOL_NAME'];
$data['EmailIds']= $_SESSION['EmailIds'];
then encode it like
$json_obj = json_encode($data);

Related

How to place php variable in javascript object in different? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Executing PHP code inside a .js file
(5 answers)
Closed 2 years ago.
I am trying to fetch data from php, store it as json and load it into my javascript code.
I stored my variable in php like this:
$data = array[];
$data = json_encode($raw_data);
Now I want to retrieve that data and use it in my javascript file.
I tried to use the following code in my js file:
var data ="<?php echo $data ?>";
[screenshot]: https://i.stack.imgur.com/pDfsf.png
If the data is only needed once on page load, you can use a script bloc inside the PHP code and then use a JS function to fetch it. But if data is being updated according to the user's interaction with the page, keep in mind that you can't send data from server side in PHP to the client side in JS without using AJAX.
I suggest you read about and use one of these 3 methods:
XHR
fetch
or axios
You are declaring the string to the variable data by using quotes.
Please remove the quotes and that would behave as per your expectations.
So your code should be replaced by the below lines.
var data =<?php echo $data ?>;
var data = <?php echo $data ?>;
or
var data = JSON.parse("<?php echo $data ?>");
The most obvious problem is your quote marks, which make the variable a string in JavaScript, rather than a complex object with a data structure. So any references to properties etc in the variable would not work. The quote marks should be removed so that the data is rendered as an object literal into the emitted JavaScript.
But there's another signficant issue: if this is being done in a .js file as you state, then the PHP interpreter is not running there, so the echo won't work (quotes or no quotes), because it isn't executed by PHP and turned into data. You'd just see the PHP code directly embedded in the JS code.
You'd have to echo the data into a script block in the .php file, then call the appropriate function in your .js file and pass the data as a parameter. This will work nicely if the data is only needed once.
e.g.
PHP file
<?php
$data = array[];
$data = json_encode($raw_data);
?>
<script src="someJsFile.js"></script>
<script>
var data = <?php echo $data ?>; //inject the data into the JS as an object literal
someFunc(data); //pass the data to a function in someJsFile.js
</script>
JS file:
function someFunc(data) {
//your code to process the data
}
If you need to keep it updated during the lifetime of the page, then you'll need AJAX to be able to request new data from the server, as suggested in one of the other answers.

Send an extra variable in Javascript to another PHP file

So I have a Javascript that sends one variable to a PHP file, now I need to add an extra variable to be sent to that PHP file. How do I go about achieving this?
I Have 3 sets of code/pages that work together to send one variable.
Main Page with Javascript:
http://pastie.org/10517825#51-76,120-122
PHP Data process page:
http://pastie.org/10517863
I have a variable called $team_id, how do I send $team_id into the external PHP file using Javascript?
So if you look at line 9 on the PHP Data process link $query variable after engineer_id I want to add the statement AND team_id='$team_id'. But I don't know how to send $team_id from the first page to the second data process PHP file.
Hello you just change in ajax call
$.post("updateList.php",{first_variable:value,second_variable:value,third_variable:value,.......}, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
I would suggest that you define the variables manually in your javascript code like this:
var order = '123456'
var team_id = 'team1'
var engineer_id = 'engineer1'
Once this is done, post them as a JSON object:
$.post("updateList.php", {order: order, team_id: team_id, engineer_id: engineer_id}, function(theResponse)
Then on the PHP side:
$order = $_POST['order'];
$team_id = $_POST['team_id'];
$engineer_id = $_POST['engineer_id'];
This should make it easier to identify variables too.

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

Store Javascript object in $_SESSION by Ajax. Array vs JSON string

I'm sending an Ajax request which sends an object objectVariable to a PHP file:
$.post(url, {action : 'function' , object : objectVariable });
Then, the PHP file will store objectVariable in $_SESSION['objectVariable'] (I'm omitting validation to make it clear):
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = $_POST['objectVariable'];
}
When the user goes to other page of the site, the $_SESSION['objectVariable'] will be sent from PHP to the user by Ajax again.
Here, I should encode the array stored in $_SESSION['objectVariable'] to a JSON string:
//inside other Axax callback function
echo json_encode($_SESSION['objectVariable']);
That's working right, but I also could store a JSON string into $_SESSION['objectVariable']:
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = json_encode($_POST['objectVariable']);
}
And after, just echo $_SESSION['objectVariable'] to send it to the Javascript file.
I wonder what would be a better way: store an array in $_SESSION['objectVariable'], or store a JSON string.
Any suggestion about it?
When sending data between Javascript/PHP I always keep it encoded as a JSON string. It makes things simpler. In fact, I would just JSON.stringify() it right away when you send it to the server the 1st time.
This way you also will always know what type the data will be.

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Categories

Resources