I have a jQuery function to print charts (jqPlot framework).
I want to print several charts with different options. So I need to call this function more than once and with different values.
I have an ugly solution like this:
//----- index.php:
// chart 1
$values = "[1,2,3]";
$id_chart = "chart1";
$options = "{...}";
include 'chart.php';
// chart 2
$values = "[8,2,5]";
$id_chart = "chart2";
$options = "{...}";
include 'chart.php';
//---- chart.php
<script>
$(function () {
$.jqplot(<?php echo $id_chart;?>, <?php echo $values;?>, <?php echo $options;?>);
});
</script>
I tried another solution - call javascript function with variables and invocate jQuery function in JS function.
//---- index.php:
<script>
function printChart(opt1,opt2,opt3){
$(function () {
$.jqplot(opt1, opt2, opt3);
});
}
</script>
<?php
// chart 1
$values = "[1,2,3]";
$id_chart = "chart1";
$options = "{...}";
echo "<script>
printChart(\"$id_chart\",\"$values\",\"$otpions\");
</script>";
// chart 2
$values = "[8,2,5]";
$id_chart = "chart2";
$options = "{...}";
echo "<script>
printChart(\"$id_chart\",\"$values\",\"$otpions\");
</script>";
?>
But off course, jQuery can not 'see' variables from JS. Is it possible to pass the variables from JS to jQuery?
Do you have, please, any other suggestions for an optimal solution?
Thank you guys.
What you need to understand is that PHP is a server side language and JavaScript is a client side language. The PHP will completely execute, generating an HTML page (containing JavaScript) and then send that to the client's browser. The browser renders the HTML and executes the JavaScript. So what you need to do is print the information for JavaScript to the page. This should suffice:
<?php // your PHP to generate the values into an array
$charts = [
[
'values' => [1,2,3]
'id_chart' => 'chart1',
'options' => '{...}'
],
[
'values' => [4,5,6]
'id_chart' => 'chart2',
'options' => '{...}'
]
];
?>
<script>
var charts = JSON.parse(<?= json_encode($charts) ?>);
$.each(charts, function () {
$.jqplot(this.id_chart, this.values, this.options)
});
</script>
Is it possible to pass the variables from JS to jQuery?
jQuery is a library for javascript.
this means that jQuery variables are javascript variables.
which means you can use them like any other javascript variables.
Related
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>")
?>
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();
I'm new at PHP and I don't understand why this happens.I try using echo to show "$imglinksis" and the result is exactly http://catpic.s3.amazonaws.com/product.jpg
I do not understand why the 2nd Code fails. Please help!
Code #1: This code completely works in returning the fields I want
<?php function CallCatpicAPI($photoUrl){do something...}
$imglinksis = "http://catpic.s3.amazonaws.com/product.jpg";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
Code #2: Fail to return: API says invalid URL image link
<?php function CallCatpicAPI($photoUrl){do something...}?>
<script>var img_link = "http://catpic.s3.amazonaws.com/product.jpg";</script>
<?php
$imglinksis = "<script>document.write(img_link).toString()</script>";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
You are mixing the two codes. Your php is executed on the server but the javascript is executed on the client side after php executed. You can fix your second code by this:
<?php
$imglinksis = 'http://catpic.s3.amazonaws.com/product.jpg';
function CallCatpicAPI($photoUrl){do something...}
?>
<script>var img_link = '<?php echo $imglinksis; ?>';</script>
<?php
$jsonReturnCatpic = CallCatpicAPI($imglinksis);
?>
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];
I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.