I would like to use PHP variable in Java Script, I would like to get the variables of longitude and latitude which is returned from Select statement read from mysql database on the server.
here with my code below and what I have tried:
<?php
...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Latitude, Longitude FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
$latlong = " ". $row["Longitude"]. " , " . $row["Latitude"]. "<br>";
echo $long; //echo's -25.1234
echo $lat; //echo's 25.1234
echo $latlong; //echo's -25.1234 , 25.1234
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Tracker</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1200px; height: 750px;"></div>
<script language="JavaScript">
var locations = [
['FirstColumnString<br/> SecondColumnString', -25.038326, 25.038326], //I would like to pass Lat Long from PHP code from above
];
// I've tried
// ['FirstColumnString<br/>SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>,
// ['FirstColumnString<br/>SecondColumnString', <?php echo $latlong ?>,
// ['FirstColumnString<br/>SecondColumnString', "<?php echo $long; ?>", <?php echo $lat; ?>,
...
</script>
</body>
</html>
You should save your locations into an array first:
<?php
$locations = Array();
while($row = $result->fetch_assoc()) {
$loc = Array("lat" => $row["Latitude"], "long" => $row["Longitude"]);
$locations[] = $loc;
}
?>
then you can pass it to javascript:
<script>
var locations = <?php echo json_encode($locations) ?>;
// check what you've got:
console.log(locations);
</script>
you could then access your values like this:
var firstLocationLatitude = location[0].lat;
If you need to have your js-array exactly as you've posted change php to:
$clmString = "FirstColumnString<br/> SecondColumnString";
while($row = $result->fetch_assoc()) {
$loc = Array($clmString,$row["Latitude"],$row["Longitude"]);
$locations[] = $loc;
}
Try replacing
$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";
with
$long = $row["Longitude"];
$lat = $row["Latitude"];
and then
var locations = [
['FirstColumnString<br/> SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>],
];
Related
I've been hanging on this problem for 3 days and just can't solve it. It seems relatively simple, but unfortunately, I can't do it, because I'm a noob.
I would like to use the button's onclick function to get its 2 pieces of information
```html
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">```
name = "'. $ row [' name '].'" [the name reference from a database
table]
and value="Pause"
this two informations i would like to store in some other database table.
I have tried to solve this problem in different ways.
I have tried to store in different ways the event.target.name & event.target.event javascript output in PHP Variables and then use it in the mysql insert line but i failed.
I have tried to post the value to the ajax.php then store the value in a PHP variable and use this as Value to push it to the database, but this also doesn't work
index.php
<div class="button2">
<form action="ajax.php" method="POST">
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">
</Form>
</div>'
script.js:
function pushDataToDB() {
$.get("ajax.php");
return false;
}
ajax.php
<?php
include_once ('dbh.php');
if(isset($_POST['name'])){
$sqlAufPause = "INSERT INTO aktuellaufpause (name, pausenart) VALUES ('$name', 'BP')";
}
if ($conn->query($sqlAufPause) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I would say this is the reason, why the name Value is empty,
but i don't know how to fix ist..
emptyNameValue
You can use JQuery + AJAX to perform asynchronous POST
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$query = mysqli_query($con, "SELECT * FROM mytable WHERE id = 1");
$row = mysqli_fetch_assoc($query);
print_r($row);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="button2">
<form id="frm">
<input id="<?php echo $row['id'] ?>" type="button" value="Pause" name="<?php echo $row['name'] ?>" onclick="pushDataToDB()">
</Form>
</div>
</body>
<script type="text/javascript">
function pushDataToDB() {
var name = "<?php echo $row['name'] ?>";
var value = "Pause";
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
</html>
ajax.php
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$value = $_POST['value'];
$query = "INSERT INTO mytable(name, value) values('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
EDITTTT****
I changed
var name = "<?php echo $row['id'] ?>";
to
var name = "<?php echo $row['name'] ?>";
since it is the "name" you want stored in the database
I solved the problem this way.
Thank you so much!!!
index.php
<?php
$sql = "SELECT * FROM `DB-TABLENAME` ORDER BY `VALUE1`, `VALUE2`";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo '<input style="margin: 0 auto 6px 17px;" type="checkbox" id="scales" name="scales">';
echo "</td>";
echo "<td>";
echo $row['VALUE1'];
echo "</td>";
echo "<td>";
echo $row['VALUE2'];
echo "</td>";
echo "<td>";
echo '<div class="button1">
<input id="'.$row['id'].'" type="button" value="BP" name="'.$row['VALUE2'].'" onclick="pushDataToDB()">
</div>';
echo "</td>";
echo "<td>";
echo '<div class="button2">
<form id="frm">
<input id="'.$row['id'].'" type="button" value="Mittagspause" name="'.$row['name'].'" onclick="pushDataToDB()">
</form>
</div>';
echo "</td>";
echo "</tr>";
}
} else {
echo "there are no comments";
}?>
<script type="text/javascript">
function pushDataToDB() {
var name = event.target.name;
var value = event.target.value;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
ajax.php
<?php
include_once('dbconnectioncredentials.php');
$con = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['VALUE1'];
$value = $_POST['VALUE2'];
$query = "INSERT INTO aktuellaufpause (VALUE1, VALUE2) VALUES ('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
?>
I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>
I use simple AJAX to display data from database. But, when i run it, only 1 data show on my table, the rest of data show outside from my table. Am i missing something ?
I use same code from my standar Bootstrap table and it show data into my table correctly, but not this one.
My PHP file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tata_kota1";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from laporan_gini";
$result = $conn->query($sql);
echo "<table border='1'>
<thead>
<tr>
<th>Nomor</th>
<th><b>tipe variabel</b></th>
<th><b>variabel turunan</b></th>
<th><b>nama atahun</b></td></th>
<th><b>turunan tahun</b></td></th>
<th><b>data_content</b></td></th>
<th><b>vertical variabel</b></th>
</tr>
</thead>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
{
echo "<tbody><tr>";
echo "<th>".$row['id']."</th>";
echo "<td>".$row['nama_variabel']."</td>";
echo "<td>".$row['nama_variabel_turunan']."</td>";
echo "<td>".$row['nama_tahun']."</td>";
echo "<td>".$row['nama_turunan_tahun']."</td>";
echo "<td>".$row['data_content']."</td>";
echo "<td>".$row['nama_item_vertical_variabel']."</td>";
echo "</tr>";
}
echo "</tbody></table></table>";
}
} else {
echo "0 results";
}
?>
You need to write tbody before the while loop.
Your problem is you have an extra set of {} inside your while and so the echo "</tbody></table></table>"; is inside the while, not outside it. Try this:
if ($result->num_rows > 0) {
echo "<tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<th>".$row['id']."</th>";
echo "<td>".$row['nama_variabel']."</td>";
echo "<td>".$row['nama_variabel_turunan']."</td>";
echo "<td>".$row['nama_tahun']."</td>";
echo "<td>".$row['nama_turunan_tahun']."</td>";
echo "<td>".$row['data_content']."</td>";
echo "<td>".$row['nama_item_vertical_variabel']."</td>";
echo "</tr>";
}
echo "</tbody></table></table>";
} else {
echo "0 results";
}
My php invoicing system uses jQuery autocomplete to lookup a customer's name from my database. The layout of the pages is like this:
invoice.php - contains the variable 'customers' and the php database select script
invoice.js - this contains the jQuery on focus command
In Safari everything works fine. I have used the console to see the variables logged - example (CUSTOMERS – ["Paul Smith"] (1))
But in Chrome and Firefox the console shows: "CUSTOMERS" Array [ ]
My code for invoice.php:
var arr_customers = new Array();
<?php $result = mysql_query("select * from customer where breaker='".$_SESSION['breaker_id']."'");?>
<?php $str = ""; $i = 0; while ($row = mysql_fetch_array($result)) { ?>
arr_customers[<?php echo $i;?>] = new Array();
arr_customers[<?php echo $i;?>][0] = "<?php echo $row['customer_name']; ?>";
arr_customers[<?php echo $i;?>][1] = "<?php echo $row['customer_code']; ?>";
arr_customers[<?php echo $i;?>][2] = "<?php echo $row['address']; ?>";
arr_customers[<?php echo $i;?>][3] = "<?php echo $row['uid']; ?>";
<?php if ($i == 0) {
$str = "'" . $row['customer_name'] . "'";
} else {
$str = $str . ",'" . $row['customer_name'] . "'";
}?>
<?php $i++;
} ?>
var customers =<?php echo ("[" . $str . "]") ?>;
and for the invoice.js:
jQuery(document).ready(function($) {
$("#customer_name").on('focus', function() {
console.log("CUSTOMERS", customers);
$( "#customer_name" ).autocomplete({
source: customers
});
});
});
I know I should be using prepared statements as well!
Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>