Add php define variable in javascript variable - javascript

I have a php varaiable that I need to pass into a link in a javascript function
//In the config
<?php
define('THE_VAR', 'test');
?>
//On the page
<?php
$the_var = THE_VAR;
?>
<script>
(function()){
link = "test.site"+<?php echo json_encode($the_var); ?>+"/testing.js"
})();
</script>
I need the link in the javascript function to read.
test.site/test/testing.js

Instead of: link = "test.site"+<?php echo json_encode($the_var); ?>+"/testing.js"
Use: link = "test.site/<?= $the_var; ?>/testing.js";

Use Ajax for passing the data from php into the javascript.
http://www.w3schools.com/ajax/ajax_php.asp

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);
}

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

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();

How to refresh a specific div content along with the link id when clicked on a link?

I am trying to refresh the div content by clicking on href link along with the id(named as data), my actual problem is I'm unable to get the id value with in the script because it is passed with in the function. How to pass the data variable in my php to script? Please check my code below and help me out to solve this. img_div is id of my div which is to be refreshed
PHP:
function printSubDir($dir, $path){
global $data;
$data = $path.''.$dir;
echo "<li><span class=\"toggle\"><a href='asset1.php?data=$data' id='refresh'>$dir</a></span>";
createDir($path.$dir."/");
echo "</li>";
}
Script:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#refresh').click(function(){
$('#img_div').load('asset1.php #img_div', function() {
});
});
});
</script>
Hi assuming that your variable is $data.You can a php variable in javascript like the following
<?php
$data = "Value of your variable";
?>
<script>
// now a javascript variable data stores the value of your php variable
var data= "<?php echo $data?>";
</script>
I Hope this heps
Echo the id into the function call:
<?php
echo "<a onClick='handleClick($id)'>$dir</a>";
?>

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.

passing value to javascript to php variable: It do not work?

In this program similar_text function do not work but echo successfully print $var_1 and $var_2. What is the exact error?
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(j)</script>';
$var_2 = '<script>document.write(l)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
PHP is executed first, on the server, then it gets served and then only javascript is executed on the client-side. so the variables you are using in php part are not set at that moment.
If you need to interact with a php script from javascript, you odd to use an ajax request.
you need close php and open again
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(?>j<?php)</script>';
$var_2 = '<script>document.write(?>l<?php)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
or same.

Categories