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})
Related
I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)
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.
I'm trying to make my website multilingual, i have the php code also and i have translated files, but my site has also js file where is this words which i want to translate, there is example of this php code and how to insert it to js file?
There is JS code
// Update search list
rsParent.html($('<div>').attr({id: 'relatedSearches', class: 'contentBox'})
.append($('<div>').addClass('cbHead').text('Related Searches'))
.append($('<div>').addClass('cbBody').html(list)));
}
});
and the word "Related Searches" i want to replace with this php code
<?php echo $lang['CHARTS']; ?>
It is not possible to do it directly since PHP is a serverside language which is executed once on a webserver, unlike javascript that is executed in client's browser.
What you can do is encode your PHP array $lang to JSON and then output it as inline javascript and assign it to a variable in javascript.
<?php
echo "<script>";
echo "var lang = " . JSON_encode($lang) . ";";
echo "</script>";
?>
Make sure this php code is placed (executed) before your javascript file because variable lang has to be declared before your javascript is executed.
Right now I have a php file that recieves a string from a search bar on page1 of my website. It queries the data bases and creates a JSON string of results. I can then use PHP to redirect my website to page2 (The search results page). How can I receive that JSON string in the Javascript of page2?
First you need a PHP file that will encode json code . Make a file like this:
http://localhost/project/myjs.php
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Then your JavaScript (in this example I use jQuery):
$.getJSON('http://localhost/project/myjs.php', function(data) {
console.log(data);
});
This should be a start to get PHP arrays in to your JavaScript.
To redirect browser to another page you have to use header function
header:('Location: http://example.com/page2.php');
You can store data in $_SESSION array between pages like that:
page1.php
session_start();
$_SESSION['array'] = array('foo'=>$bar);
page2.php
session_start();
echo json_encode($_SESSION['array']);
page1.php:
<?php
$my_array = array('foo'=>$bar);
$json_data = json_encode($my_array);
header:('Location: http://example.com/page2.php?data='.$json_data);
?>
page2.php
<?php
$data_get = $_REQUEST['data'];
?>
<script type="text/javascript">
var mydata =<?php echo $data_get; ?>;
</script>
I want to set the value of a JavaScript variable into a PHP variable. How can that be done?
Kindly give me some suggestions.
My code is :
document.getElementById("dummy").value= <?php echo ("document.getElementById('txtplan').value"); ?> //document.formn.txtplan.options[document.formn.txt'+fld+'.selectedIndex].value //eval(''); $_POST['txtplan']
alert(document.getElementById("dummy").value);
<?php
$planname = $_POST["dummy"];
$plandetails = mysql_query("SELECT * FROM membershipplan where planname='$planname'");
while($row1 = mysql_fetch_array($plandetails))
{?>
document.getElementById("txtduration").value=<?php echo $row1['planduration']; ?>
document.getElementById("txtplancontact").value=<?php echo $row1['plannoofcontacts']; ?>
document.getElementById("txtplanamount").value=<?php echo $row1['planamount']; ?>
<?php
}
?>
});
am not do with this means kindly give me the alternative way for the above process
JS -> PHP = impossible (only if you send that info to PHP using POST or GET)
PHP -> JS = possible var text = <?php echo( $text ); ?> ;
The only reason for that is that the PHP code is executed on your server.
You cant do that i.e you cant assign a javascript variable to a php variable
(unless you are using cookie or ajax) but u can assign a php variable to a javascript variable using
var a=<?php echo $a ?> ;
but be careful with that as the php variables will be executed in the server.
The answer is simple. Impossible. Because,
Java script is a client side scripting. Client machine can handle
this script, If it is possible to assign javascript value to PHP
variable that leads to some sort of vulnerability.
So this can't be done.
If you want to accomplish something by doing this kind of assignment, Definitly there would be a way of doing it. Post another question what do you want to do, you will be showered with answers.