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

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.

Related

How minify javascript function receiving PHP Arrays?

I have a javascript function receiving php arrays like this :
let options = <?php echo $arrayoptions; ?>;
let optlibs = <?php echo $arrayoptlib; ?>;
let forms = <?php echo $arrayforms; ?>;
It works well but problem arises when I try to minify function. All minifiers I tried gave en error with php part. What can I do ?
Yes, you will run into errors because PHP is not part of Javascript syntax.
Even your Javascript part for the arrays seems dynamically generated by PHP.
This will be impossible to handle.
The only way to work around this would be modify your javascript to fetch those arrays and store them somewhere your whole script can access them for later use.
Then, the script can be minified without issue since PHP syntax are no longer part of it.

Sending a PHP session variable to javascript of another file

I extracted data from a CSV file using PHP and stored the data as a nested array.
I stored this array as a session variable and now I want to access the array in another html file using javascript. How can this be done?
<?php
session_start();
$arr=array();
$arr['1']=array('abc','def');
$arr['2']=array('123','456');
$_SESSION["abc"]=$arr;
?>
This is a sample php. I have to access the session variable in javascript.
Yes, you can use implode PHP function to convert your array to string and then echo that string and assign to a JS variable like in example below.
Your another HTML file:
<?php
session_start();
$your_array=$_SESSION['your_array'];
?>
<script>
var js_variable = [<?php echo implode($your_array,','); ?>];
console.log(js_variable);
</script>
What you should be aware of, is that php is server side and javascript is client side. So to solve this, you have 2 options:
let the php code add this variables in the head. on to of everything:
<script>
var php_variables= <?php echo json_encode($your_php_variables); ?>;
</script>
or 2. Make a seperate php file which just echos only the value in json and put a json header:
<?php
header("content-type:application/json");
echo json_encode($your_php_variables);
?>
and then let javascript retrieve it. there are many libraries available for that. but lets take a comon one like jquery:
$.get("yourphpfile.php",function(data){do something here})

How to get PHP string value in javascript?

Hi have looking on various questions but none of them seem to help me. I have a php variable in my php code and I am trying to access that in my javascript when I do. . .
var thing = "<?php echo($phpvariable); ?>";
then when I do
alert(thing);
It comes out to be "<?php echo($phpvariable); ?>" in the alert statement
What am I doing wrong?
Your PHP is obviously not being parsed. Are you in a .php file? If you're in a .js file, you'll need the server to parse those (or, more safely, put the PHP part somewhere in the DOM that the JS can access)
However, you're doing it wrong:
var thing = <?php echo json_encode($phpvariable); ?>;
Note: no quotes. json_encode will take care of that for you.
If this code is in a function in javascirpt that executes on click or at a specific event, then:
You are writing PHP Syntax in javascript, there is no way that you load the page then you run the php code. PHP code runs on the server side, so before any other HTML Javascript code executes
Else if you want to dynamically set the variable thing in javascript when the page is first loaded, then most probably you meant to write in the php file:
var thing = <?php echo '"'.$phpvariable.'"'; ?>;

php and JavaScript zip code

What i'm trying to do is when a user enters a zip code in the input type i get the value of the input type store in origin_zipcode than add origin_zipcode inside the $url variable. From there it should run the xml and i should be able to display the city and state but it doesn't do that it im trying to make it work like
https://ship.onemorepallet.com/shipment/start?hsCtaTracking=296d76b9-a6fc-4140-83f9-de066c986716|9001d544-e760-4dae-ac72-36cc2922be55?utm_referrer=http%3A%2F%2Fwww.onemorepallet.com%2F
when you enter in the zip code
$("#origin_zipcode").keyup(function(){
var origin_zipcode = $("#origin_zipcode").val();
<?php
$url = "http://zipcodedistanceapi.redline13.com/rest/gNPseXsQyP3daTlKfRB3D0v0mPVC3jJj6zMlwec54fie8EZowAsaBXaXN5zQpjav/info.xml/origin_zipcode/degree";
$xml = simplexml_load_file($url);
$city = $xml->city;
$state = $xml->state;
?>
$(".labelzip").text(<?php echo $city,$state"; ?>);
});
You can't send a jQuery variable to a PHP script unless you refresh the page using one of a few possible methods. This is because while jQuery is client-side, php is server-side. After PHP has finished loading the page, it can't be used again without a page reload.
You can look at these questions for a possible solutions:
How to pass jQuery variables to PHP variable?
jquery 'variable' to php 'variable'
how to pass a jquery variable to php and then display it

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