Passing php database result to javascript array - javascript

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!

Related

inject last part of URL dynamically and uniquely using javascript or php

I am trying to work out how to get thye last part of a url on click of a button dynamically from a pre populated csv file.
For example on click of <a href="mysite.com/" >button</a>
would grab a code from a CSV file (or something better) and the link would be mysite.com/code1.
However each code from the CSV will only be used once and be removed after
So first click = mysite.com/code1
Second click = mysite.com/code2
and so on getting code1 and code2 from the CSV file and never to be gotten again.
I can use either JavaScript or PHP, either is good, I'm just not sure on the syntax.
Like this:
<?php
$first = true;
$links = "";
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if (!$first) $links.=",";
$first=false;
//$line is an array of the csv elements
$links.='"'.$line.'"';
}
fclose($file);
?>
Plain JS
<script>
var links = [<?php echo $links ?>];
cnt = 0;
window.onload=function() {
document.getElementById("csvLink").onclick=function() {
window.open(this.href+links[cnt],"_blank"); // otherwise you need cookies
return false;
cnt++;
}
}
</script>
jQuery using Ajax:
<script>
var links = [<?php echo $links ?>];
cnt = 0;
$(function() {
$("#csvLink").on("click",function(e) {
e.preventDefault();
$("#someContainer").load(this.href+links[cnt]);
cnt++;
});
});
</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];

Passing Array Index numbers from PHP to 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 !*

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

How to bring PHP array value to Javascript?

<html>
<head>
<script language="javascript">
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+window.document.contact[i].value);
}
return false; //to prevent form from submitting for debugging
}
</script>
</head>
<body>
<form name="editform" onsubmit="return validatefrm();" method="POST">
<?php
for($i=0; $i<3; $i++){
print "<input type='textbox' id='contact".$i."' value='".$i."'>";
}
?>
<input type="submit" value="Submit Values">
</form>
</body>
</html>
Hi, I'm new to php and javascript.
I'm trying to call the form with the value of 0,1,2 with javascript but it wont work. Unless i delete the for loop in javascript function and hard code it as Window.alert (window.document.contact0.value) and so on....Anyone can help? Must appreciate.
If I get your question correctly, you need to access the elements by ID. And the correct way is to use document.getElementById(...). In your case:
for (var i= 0 ; i< 3 ; i++){
window.alert(document.getElementById('contact' +i).value);
}
You are setting an ID for each element with php contact0, contact1 etc.
So in javascript look for that ID
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+ ' '+ document.getElementById('contact'+i).value);
}
return false; //to prevent form from submitting for debugging
}
Your best choice would most likely be to use json_encode. This method outputs the array as a JSON array which can be assigned to a JavaScript variable in <script> tags. Associative arrays on the PHP side would get converted into JSON objects.
json_encode in the PHP documentation
<?php
$myArr = array(0, 1, 2);
?>
<!-- somewhere in the HTML document -->
<script>
var myArr = <?php echo json_encode($myArr); ?>;
// do something with myArr
console.log(myArr);
</script>
The php is executed on the server side, before it makes it to the browser. The javascript is executed on the client side, in the browser. You cannot pass php values to javascript like this.
You can make the php output javascript (in a script tag), and use that in your javascript code though.
<script>
var foo = [];
<?php
for($i=0; $i<3; $i++){
print "foo[".$i."] = ".$i;
}
?>
console.log(foo[0] + ", " + foo[1] + ", " + foo[2]);
<script>

Categories