This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a small issue. I can't seam to pass a variable from PHP to JS.
Here is my JS:
var eName = '<?php echo $eName; ?>';
I know that $eName has a value. However in the JS section, I get nothing. no data seams to be present in the variable. when I echo in the PHP section, I get data.
Can anyone help?
Also tried:
var eName = '<?php echo json_encode($eName); ?>';
This give me a null result
Thanks for your help
Here is how I get my PHP Variable populated:
$sql="SELECT * FROM league WHERE id='". $lID ."' LIMIT 1";
$result = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($result);
if($numrows < 1){
echo "league does not exist";
exit();
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$eName = $row["name"];
According to your edited code, I guess your variable $eName would be empty for the last record of the while loop.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$eName = $row["name"];
// if the last record has the empty value for the field `name`,
// it will overwrite the previous value and
// you will get `$eName` of no value out of the loop later
}
And moreover, make sure you are not using <?php ?> in the .js file which is not parsed by Javascript.
Related
I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>
basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML
<?php include('ConnectionCode.php');
$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());
$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);
echo json_encode(number_format($price['RetailPrice'],0,".",","));
mysqli_close($conn)
?>
the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML
<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything
I would greatly appreciate your input
Update:
You may also have a problem with using json_encode inside of "" quotes.
var PriceValue = "<?php echo json_encode($price) ?>";
Instead, use:
var PriceValue = <?php echo json_encode($price) ?>;
or
var PriceValue = <?php echo $price ?>; // if $price is not an object
Note:
To debug this, check the generated HTML source to see what JavaScript you are actually generating.
$price needs to be in the same scope when you try to generate JS.
http://phpfiddle.org/main/code/aeav-gb1w
<?php
$price = 2523525;
?>
<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.
Recently I have been assigned a group project for a college class and I will need to query a customers name from a database and then print out the rest of the row in form fields. I have the select menu working correctly and it will print to the form field. However, the problem occurring is the query results will only show the last row in the MYSQL table I selected. Any help here would be greatly appreciated. I have been spinning my wheels for a few days on this issue. I am only a beginner coder, so it might be a little messy.
Thanks,
Connection.PHP File
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "medley";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
My Query Page
<?php
require 'connection.php';
$conn = Connect();
$sql = "SELECT * FROM cust_info";
$result = $conn->query($sql);
echo "<select id='firstName' name='firstname' onchange=populatesecondbox()>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['F_Name'] . "', '" . $row['L_Name'] . "'> " . $row['F_Name'] . " " . $row['L_Name'] . "</option>";
$pphone = $row['P_Phone'];
}
echo "</select>";
?>
<input id="secondinputbox" type="text" />
<script type="text/javascript">
function populatesecondbox(val) {
var dropdown = document.getElementById("firstName");
var pphone = document.getElementById("secondinputbox");
var secondfname = document.getElementById("thirdinputbox");
var str = "<?php echo $pphone ?>";
var sfname = "<?php echo $sfname ?>";
pphone.value = str;
secondfname.value = sfname;
}
</script>
Instead of using
$row = mysqli_fetch_array($result)
on line 10, use
$row = $result->fetch_assoc()
or
$row = $result->fetch_array()
The difference between fetch_assoc and fetch_array is that fetch_array contains both numeric indices and named indices. For example echo $row[0] will output as same as echo $row['id']. Whereas, fetch_assoc only contains named indices.
Based on the provided loop statement
$pphone = $row['P_Phone'];
$pphone is getting assigned to the last row on termination of the loop because each iteration is overriding $pphone with the current row until at which point in the loop $pphone gets the last value.
Instead of using
$pphone = $row['P_Phone'];
Try the following in the loop.
$pphone[] = $row['P_Phone'];
Your concatenated phones should be provided after the loop.
$pphones = "['".join("','" , $pphone)."']";
In your js script tag just get $pphones as a string;
var pphones = <?php echo $pphones; ?>;
ddl = document.getElementById('firstname');
pphone.value = pphones[ddl.selectedIndex];
I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)
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.