I am attempting to get all the data from a MySQL db with PHP, initialise a 2D java array and populate it with the PHP data.
I am having trouble embedding JS in the PHP. I have marked up what is working and what isn't.
As you will see, some of the embedded java works but not all.
Any thoughts?
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
string [][] hhgdata = new string[numrows][4]; // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter + "<br/><br/>"); //THIS WORKS
hhgtitle = <?php echo $hhgtitle; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write(hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?
$counter++; // THIS WORKS
}
?>
</body>
You are mixing up Java and JavaScript. For example this is Java syntax, you can't write this within a script tag which should only contain JavaScript:
string [][] hhgdata = new string[numrows][4];
The JavaScript arrays are dynamic, this should be enough:
var hhgdata = [];
When you want to add another array into it, as you seem to be doing later in your code, just do this:
hhgdata[counter] = [];
And then assign to the inner array:
hhgdata[counter][1] = hhgtitle;
You are also creating multiple assigning an unquoted string literal to variable with this (assuming $hhgtitle contains a string):
hhgtitle = <?php echo $hhgtitle; ?>;
It should be something like this:
hhgtitle = <?php echo '"' . $hhgtitle .'"'; ?>;
Finally, while it's not incorrect, your PHP while loop is creating multiple script elements in your HTML.
EDIT
I have made the changes described above as well as in comments, copy-paste exactly and see how it goes:
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
var hhgdata = new Array(numrows); // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?php
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
var counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter); //THIS WORKS
hhgtitle = <?php echo '"' . $hhgtitle . '"'; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter] = [];
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write("<br />hhgdata[counter][1]: " + hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?php
$counter++; // THIS WORKS
}
?>
</body>
Why not just take the PHP array of data and json_encode it? Then you can work with it in Javascript, see below:
var json = <?php echo json_encode($foo); ?>;
You can learn more about how to do this here: http://www.openjs.com/scripts/data/json_encode.php
Related
I am beginner in the PhP and Jquery. So, may be the solution to this question will be easy. I am successfully updating table using ajax and PhP. The issue is that table is updated by removing the all the data, and then populating new data.
I am looking for any other approach. After getting new data through PhP, compare new data with old data,...if there is some issue in hardware, then change the status..also keep the time from which the hardware stopped working. I ask question before Put data from Postgresql database to table using Ajax and PhP, in which #Mcsky suggested me a solution, but I did not get his approach. So, How to update table data only?, instead of complete refresh of table, which feels like page refresh. here is my client code: estat_hardware.php
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagsDiv">
<h3>Estat Tags</h3>
<?php
echo '<table id="tags_table">';
echo "<thead>";
echo "<tr>";
echo '<th>' . "TAG" . '</th>';
echo '<th>' . "BATERIA" . '</th>';
echo '<th>' . " VIST ĂšLTIMA COP " . '</th>';
echo '<th>' . "ESTAT" . '</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "</tbody>";
echo '</table>';
?>
</div>
</div>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function(){
UpdateHTMLTable();
setInterval(function() {
UpdateHTMLTable();
}, 5000); // 5000 millisecond(5 second)
function UpdateHTMLTable(){
/* $('#tags_table tbody').empty(); */
$('#tags_table tbody').html("");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (i = 0; i < data.length; i++) {
console.log(data[i]);
var row = $("<tr />");
$("<td />").text(data[i].mac).appendTo(row);
$("<td />").text(data[i].battery).appendTo(row);
$("<td />").text(data[i].ts).appendTo(row);
$battery_beacon=data[i].battery;
if($battery_beacon<15)
{
$status="Canvi Batteria";
}
else{
$status="Correcte ";
}
$("<td />").text($status).appendTo(row);
row.appendTo('#tags_table');
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>
</body>
</html>
Server code is:
<?php
header("Content-Type: application/json; charset=UTF-8");
$host = ip";
$port ="portNumber";
$user = "abc";
$pass = "....";
$db = "name";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "query string for database";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
if(pg_num_rows($result))
{
$data=array();
while($row=pg_fetch_array($result))
{
$data[] = array(
'mac'=>$row['mac'],
'ts' =>$row['ts'],
'battery'=>$row['battery']
);
}
echo json_encode($data);
pg_free_result($result);
pg_close($con);
}
?>
I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php
I have a page that has primarily dynamic content generated by Ajax. It is randomized every 30 seconds, and new content from the database appears. The PHP seems fine, but there either seems to be something wrong with my Javascript code or there is a problem on the database causing it to lag (the Ajax takes about 30 seconds to load!)It would seem as if the recursive call to setInterval in my Javascript is waiting the alloted milliseconds before executing the function, but I can't find any errors in my Javascript.Also, there are two image url Strings retrieved from the database, and it seems plausible that Ajax would lag when it has to retrieve information from external sources.Or maybe is there a lag in my usage of the PHP-MySQL syntax ORDER BY rand()?Here is the relevant html:
<html>
<head>
<title></title>
<script type = "text/javascript" src = "randomProducts.js" />
<script type = "text/javascript">
setIntervalOnload();
</script>
</head>
<body>
...
...
...
</body>
</html>
Here is the relevant Javascript:
// global static variables
var subCategory; // initialized from setCategoryTree
var t; // for setInterval and clearInterval
var seconds;
var millisecondsPerSecond;
var milliseconds;
function setIntervalOnload()
{
getRandomProducts();
if(typeof t != "undefined")
clearInterval(t);
seconds = 30;
millisecondsPerSecond = 1000;
milliseconds = seconds * millisecondsPerSecond;
t = setInterval(getRandomProducts, milliseconds);
}
function getRandomProducts()
{
//window.alert(subCategory);
if(typeof subCategory == "undefined")
subCategory = "all";
else
{
clearInterval(t);
t = setInterval(getRandomProducts, milliseconds);
}
var req = new XMLHttpRequest();
var products = document.getElementById("products");
req.onreadystatechange = function()
{
if( (req.readyState == 4) && (req.status == 200) )
{
var result = req.responseText;
products.innerHTML = result;
}
};
req.open("GET", "randomProducts.php?category=" + subCategory, true);
req.send(null);
}
function setCategoryTree(link)
{
var categoryTree = document.getElementById("categoryTree");
/* climbing the DOM-tree to get the category name (innerHTML of highest "a" tag) */
var category = link.parentNode.parentNode.parentNode.getElementsByTagName("a")[0].innerHTML;
subCategory = link.innerHTML;
categoryTree.innerHTML = "==> " + category + " ==> " + subCategory;
getRandomProducts();
}
...and here is the relevant PHP:
<?php
// connect to MySQL
$dbName = "blah";
$db = mysql_connect("localhost", $dbName, "asdf");
if (!$db)
{
echo "<p>Error - Could not connect to MySQL</p>";
exit;
}
// select the blah database
$blah = mysql_select_db("blah");
if(!$blah)
{
echo "<p>Error - Could not select the blah database.</p>";
exit;
}
// fix html characters in $subCategory
$subCategory = $_GET["category"];
trim($subCategory);
$subCategory = stripslashes($subCategory);
$subCategoryFixed = htmlspecialchars($subCategory);
// for loop for each random product (total of 10 random products)
for($i = 0; $i < 10; $i++)
{
// query the blah database for all products
if($subCategoryFixed == "all")
{
$query = "SELECT * FROM products ORDER BY rand();";
$result = mysql_query($query);
}
else // query the blah database for products in selected subCategory
{
$query = "SELECT * FROM products WHERE cat = " . $subCategoryFixed . " ORDER BY rand();";
$result = mysql_query($query);
}
if (!$result)
{
echo "<p>Error - the query could not be executed</p><br />";
$error = mysql_error();
echo "<p>" . $error . "</p>";
exit;
}
$row = mysql_fetch_array($result);
$productValues = array_values($row);
$name = htmlspecialchars($productValues[3]);
$price = htmlspecialchars($productValues[5]);
$img = htmlspecialchars($productValues[7]);
// product info is formatted for home.html here
$str = '<div>
<a href = "' . $link . '" title = "' . $name . '">
<table id = "product-table" onmouseover = "darkenProduct(this);" onmouseout = "lightenProduct(this);">
<tr>
<td>' . $name .'</td>
</tr>
<tr>
<td><img src = "' . $img . '" /></td>
</tr>
<tr>
<td>' . $price . '</td>
</tr>
</table>
</a>
</div>';
echo $str;
} // end of products for loop
?>
You are not running your code inside of onload method. It is possible that the AJAX setup code runs faster than the page can load so var products = ... is null. You need to do something like the following:
<body onload='setIntervalOnload();'>
or
window.onload = setIntervalOnload;
setInterval does not call the function immediately. The first run of the function will be delayed by however much the interval is.
You have to specifically call the function yourself if you want it to run immediately as well as on a timer.
I am selecting some data from my database and I can echo it with PHP in my document. How can I straight pass it to JavaScript, or it its not duable, how do people deal with these things?
Here is how I get and echo:
$q=mysql_real_escape_string($_GET['q']);
$query="SELECT * FROM contacts WHERE id = '".$q."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo "Name: " . $row['first'] . " <br />";
echo "Surname: " . $row['last'] . " <br />";
}
mysql_close();
This is a quick and simple way to get this setup.
echo("<script>");
echo("var myJSvar = " . json_encode($row) . ";");
echo("</script>");
Then in any JS from there you can use myJSvar;
alert(myJSvar['first'] + " " + myJSvar['last']);
<div id="name">
<?php echo $name; ?>
</div>
<script type="text/javascript">
//jquery example
$(document).ready(function(){
alert($('#name').text());
});
</script>
$x is a string (or anything else really, just make sure the types are compatible before passing them)
$x = phpvar
echo "<script type='text/javascript'>
function Javascript_function(){
var passed = ".$x."}</script>";
That should do it. Don't forget the script <> tags, SO wouldn't let me insert them probably to prevent me just throwing javascript on every page.