Passing Array Index numbers from PHP to Javascript - javascript

new to JS and PHP and modifying a slideshow script to dynamically display contents of three different directories. Pretty much keeping things simple to start off with.
One problem I have is that the script I am modifying used the following static code to fill the javascript array:
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
variableslide[2]=['team_a/futuristic.jpg']
variableslide[3]=['team_a/lambo.jpg']
My PHP code is working so far to enumerate the directories dynamically and then pass the result on to Javascript:
<?php
// Header("content-type: application/x-javascript");
$team_a = array();
$team_b = array();
$team_c = array();
foreach (new DirectoryIterator('team_a') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_a[] = "team_a".'/'.$fileInfo->getFilename();
}
foreach (new DirectoryIterator('team_b/') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_b[] = $fileInfo->getFilename();
}
foreach (new DirectoryIterator('team_c') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_c[] = $fileInfo->getFilename();
}
?>
<script type="text/javascript">
var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>
When I "inspect element" in Chrome whilst running the full code, I can see that the file names are being passed to Javascript, but, missing the 0,1,2,3,4 etc. I only end up with the file path. Here's the result:
var variableslide = ["team_a/blank.jpg","team_a/ford.jpg","team_a/futuristic.jpg","team_a/lambo.jpg"];
What I've been Googling around is how to get var variableslide array to read as such:
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
To pull the array index number and the filename from PHP and populate the variableslide array in JS so it reads the same as above. When I print_r from the PHP script, it shows the index number and text correctly. Can anybody please help me figure this one out! Thanks!

if you wont it to look like this
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
in the php file use
<script type="text/javascript">
<?php
foreach($team_a as $i=>$v){ echo 'variableslide['.$i.']="'.$v.'";'."\n";}
?>
insetad of
<script type="text/javascript">
var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>
* ***Just notice that is the exact same thing !*

Related

Trying to get php tables into pdf format – using jsPDF-auto-table to get the result of php query(multiple records)into a nicely formatted pdf file

I'm a 'newbie' on stackoverflow but it is a source that I keep coming to regularly for tips.
I've picked up some code from the simple.html file accompanying the jsPDF auto-table plug-in but as it doesn't appear to pick up data from a php generated table.
I am trying to get the data into a format that can be transformed into a nice pdf report - 'with all the trimmings' - ie; page-breaks, headers on each page, alternate row-colours etc.
I've tried to get the data into a form that can be used by the jsPDF autotable but I'm going wrong in that it is just going through the array and keeping the last record and printing that in pdf format. Code shown below.
<button onclick="generate()">Generate pdf</button>
<script src="/js//jspdf.debug.js"></script>
<script src="/js/jspdf.plugin.autotable.js"></script>
<?php
$link = mysqli_connect('localhost','user','password','database');
if(!$link)
{
echo 'Database Error: ' . mysqli_connect_error() ;
exit;
}
$results=array();
$sql_staff = "SELECT staff_id, staff_firstname, staff_lastname, staff_username, staff_chargerate, staff_lastlogin FROM tblstaff ORDER BY staff_lastname ASC, staff_firstname ASC ";
$result_staff = mysqli_query($link,$sql_staff);
while($row = mysqli_fetch_array($result_staff)){
$results[0] = $row['staff_id'];
$results[1] = $row['staff_firstname'] . " " . $row['staff_lastname'];
$results[2] = $row['staff_username'];
$results[3] = $row['staff_chargerate'];
$results[4] = $row['staff_lastlogin'];
echo json_encode($results);
$data = json_encode($results);
}
?>
<script>
function generate() {
var head = [["ID", "Staff Name", "Username", "Charge-rate", "Last Log-in"]];
var body = [
<?echo $data;?>
];
var doc = new jsPDF();
doc.autoTable({head: head, body: body});
doc.output("dataurlnewwindow");
}
</script>
I think that the problem lays around the line $data = json_encode($results); but I don't know enough about either PHP or Javascript to determine how the code needs to be altered to produce a full PDF report. Can anyone assist please?
Your issue is probably related to overwriting the values in the $results array which means you will get one item instead of an array of items. You probably want something like this:
$results = array();
while($row = mysqli_fetch_array($result_staff)){
$dataRow = array();
array_push($dataRow, $row['staff_id']);
array_push($dataRow, $row['staff_firstname'] . " " . $row['staff_lastname']);
// etc
array_push($results, $dataRow);
}
$data = json_encode($results);

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

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];

Passing php database result to javascript array

I have to create a dropdown list and a button that will add another dropdownlist once click. i used this javascript code:
var array = ["Volvo","Saab","Mercades","Audi"];
var cell2 = row.insertCell(1);
var element2 = document.createElement("select");
element2.name="activity_dropdown"
element2.id="activity_dropdown"
cell2.appendChild(element2);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
element2.appendChild(option);
}
but i want that my var array will come from the database result query. what can i do to pass php array to javascript array?
by the way.. i have tried to used json_encode but it seems not working.. here is the my code:
for data.php
<?php
include('connection/dbConn.php');
// get data and store in a json array
$activity=$conn->query("SELECT activity_name FROM rehab_activities");
while ($row =mysqli_fetch_array($activity)) {
$activities[] = array(
'actvityName' => $row['activity_name']
);
}
echo json_encode($activities);
?>
and try it here, but nothing comes out:
<script>
jQuery(document).ready(function(){
jQuery("#add").click(function(){
var res = new Array();
jQuery.getJSON("data.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
</script>
<body>
<input type="button" id="add">
<div id="result"></div>
</body>
</html>
Make php write that part of your script while it loops through your query. Like so:
var array = [
<?php
$query = mysql_query("SELECT * FROM cars");
while ($car = mysql_fetch_assoc($query)) {
$car_name = $car["name"];
echo "'$car_name',";
}
?>
];
For this to work, your file must be a php file and not a javascript file, since inside a php file you can also write html and therefore, javascript.
I personally solve this by making a file called db-to-js.php that only contains javascript arrays created by php. Whenever the database is modified, one or more of these javascript arrays are also modified since they are created every time this file is executed.
Lastly, you have to include the file where you need it as a script:
<script type="text/javascript" src="db-to-js.php"></script>
I hope this helps.
I had a similar problem in vue js, renamed my 'app.js' file to 'app.php', where i added all my php functions and changed the reference script tag to
<script> type='text/javascript' src='app.php' </script>
Worked For me!

Inserting MySQL results from PHP into JavaScript Array

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.

Categories