use var from function.php file into scripts.js file - javascript

I have a function.php code simple one:
$var = "7000";
and I have another file script.js:
var Price = <?php echo $var ?>;
now it works when this code in the same file.
but when I separate the files its doesn't.
any suggestions?

As pointed out by GrumpyCrouton in his comment to you, variables out of one file can be read in another by including them
<?php
include('file1.php'); // include the file where the variable is defined
<script>
var Price = <?= json_encode($var) ?>; // in javascript code export the variable to js usign json
</script>
It is always safe to use json_encode and dump the variable directly into js no need to encapsulate it any more then that, I would add a semicolon at the end but that is more of a personal preference in this day and age.

Create a script called price.php with the following content:
<?php
header("Content-type: text/javascript"); // As suggested by Mark Eriksson
$var = "7000";
?>
const PRICE = <?php echo $var; ?>;
Now you can reference this JavaScript block on any HTML page:
<script src="price.php"></script>
You will have a global JavaScript variable (constant) called PRICE.
Do you need variable prices? No problem, you can pass a value as a parameter, for example:
<script src="price.php?price=8500"></script>
And in your price.php, you change it to:
<?php
$var = $_GET["price"];
?>
const PRICE = <?php echo $var; ?>;
Your HTML page still gets a constant named PRICE.

Well, if you want to access some PHP variables, then you need to use AJAX.
Its quite simple.
Do this inside function.php file
<?php
$var = "7000";
// Put your price into array to form it into JSON format further
$data = ["price" => $var];
return json_encode($data);
And following in your JS file.
let xhr = new XmlHttpRequest();
xhr.open('get', 'function.php', true);
xhr.onload = function() {
if (this.status == 200) {
var data = JSON.parse(this.response);
// Your final result
var Price = data.price;
}
}
xhr.send();

Related

How to pass data JSON string from PHP to external javascript

I have a php page that loads a JSON object string from a text file. I want to send the object string to an external javascript file which will eventually use it to update html displayed from the php page. Unfortunately I've had trouble getting the string to the external javascript.
I've been trying to follow the approach outlined by Afzal Ahmad here
Pass Php Arrays to External Javascript File
but I get no results
The php:
<?php
session_start();
echo 'Hello ' . $_SESSION['first'] . '<br>';
loadUserData();
displayPage();
function loadUserData(){
$userString = 'userdata/'.$_SESSION['email'].'.txt';
echo $userString;
$user = file_get_contents($userString);
}
function displayPage(){
/*html stuff here*/
}
?>
<script type="text/javascript">var userObj = <?php echo json_encode($user); ?>;</script>
<script type="text/javascript" src="scripts/index.js"></script>
The javascript:
console.log(userObj);
Your loadUserData function isn't returning anything.
You should remove the echo $userString; and add a return $user after the file_get_contents.
And you should change the loadUserData(); to $user = loadUserData();
That happens because you haven't declared $user in the function loadUserData as a global variable.
To fix the issue, you'll have to use the global keyword:
function loadUserData() {
global $user;
$userString = 'userdata/'.$_SESSION['email'].'.txt';
echo $userString;
$user = file_get_contents($userString);
}

Access javascript variables on server php file via browser javascript

using javascript code in browser to access javascript variable in server php file
( the php file search a text file and returned result as a php variable, then I set that php variable as javascript variable)
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
?>
//text file on server
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
//Java script code in browser.
var xhr = new XMLHttpRequest();
xhr.open("GET","http://.........data.php",false);
xhr.send(null);
$Variables.setValue(5, 'varxxx');
I got
reference error
x is not defined
if I just run http://.........data.php , it shows Search returned:"Bong"
it means data.php successfully returned the result, and php $linea is Bong.
so this part below in the php file is what causes the error?
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
or something wrong with my Javascript code in browser?
Any help is appreciated
Thanks in advance
Try "echoing" the script tag to the .html body.
You're getting this error because the variable is being created on the server side only, thats why the variable is not defined. Also I recomend you to use let instead of var, let is more secure in terms of scope.
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
?>
// New script
<?php
echo("<script> var varxxx = ".$linea." </script>")
?>

Expression expected in PhpStorm when using php variables in JavaScript functions

When I am using changing php variables to JavaScript variables, I am getting "expression expected" error from PhpStorm.
I cannot change the extension of the file to something.js.php because I am already using blade template so it should be blade.php
<!DOCTYPE html>
<html>
<body>
<?php $myVar = 5;?>
<script type="text/javascript">
var myJavascriptVar = <?php echo $myVar; ?>;
var myJavascriptSecondVar = {{$myVar;}};
alert(myJavascriptVar + myJavascriptSecondVar);
</script>
</body>
</html>
I have added a sample html page for more clarification. In PhpStrom the
var myJavascriptVar = <?php echo $myVar; ?>;
and
var myJavascriptSecondVar = {{$myVar;}};
statements gives expression expected error.
That's a bug (incomplete inter-language handling) in PhpStorm.
https://youtrack.jetbrains.com/issue/WI-24968
https://youtrack.jetbrains.com/issue/WI-25739
possibly some another (from "Related" list) as well
Watch those tickets (star/vote/comment) to get notified on any progress. Right now they are not assigned to any specific future versions.
Here are two workarounds:
1. function
function blade(_)
{
return _;
}
var data = blade({{ $data }});
// or ES6 arrow function
var data = (_ => _)({{ $data }});
2. array
var data = [{{ $data }}].pop();
// or
var data = [{{ $data }}][0];

PHP to Javascript passing variable returns null results

Here is the code that I have:
https://jsfiddle.net/a6kukf3n/
The PHP variable $weekParses contains the following data:
WK 14,WK 15,WK 16,WK 17,WK 18,WK 19,WK 20,WK 21,WK 22,WK 23,WK 24,WK 25,WK 26,WK 27,WK 28,WK 29,WK 30,WK 31,
However, when I add it to the var weekCases on Javascript and try to print it to the console or my charts.js file it returns null, 1, 2 ,3 ,4 etc
What am I doing wrong? How do I send my PHP variable to JS?
Please create a new array in php and assign the value to array
$data_week=array();
while ($weeks = mysqli_fetch_row($numRowsQuery))
{
$data_week[]=$weeks
}
After that please try
<script type="text/javascript">
//pass php variable to js for open cases pw
<?php $weekParse = $data_week; ?>
var weekCases = <?php echo json_encode($weekParse); ?>;
</script>
Prepare PHP variable inside the PHP code and not in script tag
so in your PHP code write
$weekParse = json_encode($weeks);
And your script
<script type="text/javascript">
//pass php variable to js for open cases pw
var weekCases = '<?php echo $weekParse; ?>';
</script>
Hope this helps you.

Trouble with php variables and ajax javascript

ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>

Categories