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.
Related
I'm trying to fetch row so i can print it on my table. But the problem is that, the code only runs on the 1st while loop. After it fetch all the rows in the table, it stops there.
`Assuming that I have 5 rows in my tblUnit
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('1');</script>";
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel from tblFloors where floorID = $floorNumber");
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while ($u = $t->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('2');</script>";
$floorLevel = $u['floorLevel'];
while ($x = $w->fetch(PDO::FETCH_ASSOC)) {
echo " <script type'text/javascript'> alert('3');</script>";
....
...
..
}
}
}
The output(In alert box):
1
1
1
1
1
I'm using MS SQL Server for my database.
Could be a string evalueting problem try thsi way
$t = $db->query("select floorLevel from tblFloors where floorID = " . $floorNumber .";");
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = " . $unitType . ";");
or
$t = $db->query("select floorLevel from tblFloors where floorID = '$floorNumber' ;");
Otherwise your $floorNumber don't contain the aspected result
I have two drop down list in the main page, when the user clicks on the country drop down(on change) another drop down list would be shown with the product list. This I accomplish using an ajax call (getproduts.php) from the country drop down list. The screen shots, the ajax call and the programs are attached .
The dropdown list works well and I can select the item too. The drop down list has the both the product description and the price in it.
I would like to get the price in a variable to be used in the main program when ever the user selects the option.
The sub total value(attached screen) in the main program should change with the price from the dropdown box when ever the user selects the product.
How can I achieve this?.
Ajax call
<script type="text/javascript">
function get_products()`enter code here`
{
var country = $("#country").val();
var type = $("#type").val();
var dataString = 'country='+ country + '&type=' + type;
$.ajax({
type: "POST",`enter code here`
url: "getproducts.php",
data: dataString,
success: function(html)
{
$("#get_products").html(html);
}
});
}
</script>
getproducts.php
<?php
error_reporting(1);
//print_r($_POST);
include('function/db_connect.php');
//session_start();
$price = Null;
//$items = Null;
if($_POST)
{
$var1 = $_POST['country'];
$var2 = $_POST['type'];
if ($var1 != '') {
echo "<label>Item<span style='color:red'>*</span></label><span style='color:red'></span></label><span class='address'>";
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this.value)'>";
$sql = "SELECT * FROM tbl_product WHERE country_id = '$var1' AND type_id = '$var2'";
$db = new DB_CONNECT();
$result = mysql_query($sql);
$myarray = array();
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result)) {
$idp = $row["product_id"];
$iddes = $row["product_desc"];
$selp = $row["product_sell"];
$costp = $row["product_cost"];
echo "<option value='" . $idp . "'>" . $iddes . "==>".$selp ."</option>";
}
echo "</select><label>Item</label></span><span class='address'>";
}
echo "</div>";
echo "<br>";
echo "<div><label></label><span class='name'><button name = 'data' type ='button' onclick= 'valprice('items')'>Validate value</button></span></div>";
}
?>
Right now in your select html element, you're using onChange='get_price(this.value), this line of code only get the option value in this case only $idp = $row["product_id"];. If you want to select others field, then you need to attach those values into option itself during looping process occured. Here is the example usage.
In your option tag, change into this :
echo "<option value='" . $idp . "' data-price='" . $selp . "'>" . $iddes . "==>".$selp ."</option>";
You see i adding data-price='" . $selp . "' as a user defined attribute. This later on we fetch at onchange event.
After that, change your select HTML element onchange into this :
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this)'>";
Finally, in your get_price() function tweak into this below code :
<script>
// array variable to store product details[id and price in this case]
var myProduct = [];
function getPrice(e) {
// set to empty for initial
myProduct.length = 0;
// fetch price
var price = $('option:selected', $(e)).data('price');
// fetch val ID
var valID = $(e).val();
// insert into array variable as a javascript object
myProduct.push({
ID : valID,
price : price
});
console.log(myProduct);
}
</script>
To fetch another fields, put another data-attributes like example above.
DEMO - check console to see the output
I am trying to send a value for an item in a MySQL table and increment its "availability" column by one.
A press of a button executes the following onclick function:
function updateStuff() {
// Data validation for string variable val
// coordinating to one of the items in the SQL table
var xmlHttp = false;
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xmlHttp = new XMLHttpRequest();
}
if(!xmlHttp)
alert("Error : Cannot create xmlHttp object");
else{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
xmlHttp.open("GET","update.php?val=" + val, true);
xmlHttp.send();
}
else{
setTimeout(updateStuff,1000);
}
}
}
update.php looks like this:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$item = $_GET['val'];
echo 'You selected ' . $item;
$server = "localhost";
$user = "root";
$pass = "";
$datab = "checkout";
// Connect to database
$db = mysqli_connect($server, $user, $pass, $datab);
// Check connection
if (mysqli_connect_errno()){
echo "Could not connect to database: " . mysqli_connect_error();
}
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " + $item);
// Close connection
mysqli_close($db);
echo '</response>';
?>
I think this is generally correct, unfortunately I'm not getting a table update when I execute the code. I am 100% confident in the validation for the variable val, and fairly confident with updateStuff(), but I'm less sure if I'm handling the server-side stuff corecctly with putting $_GET inside of response tags.
EDIT: I have made the syntax correction given by asparatu, but the problem persists.
The update query is wrong.
$result = mysqli_query($db, "UPDATE inventory SET available = available + 1 WHERE item = " + $item);
Where are you getting the current number for available?
you need a select statement that queries the current item and get current available amount then you can add one to it.
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " . $item);
That should work..
try this to update query:
$result = "UPDATE inventory SET available = "' .$available. '" WHERE item = "' .$item. '"";
if (mysqli_query($db, $result)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
I have two sets of code Loadmore Button And Jqueury Drag N Drop but they do not work as one.
How can I merge them together to function as one code?
Here is the Problem:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript">
This Line is needed by the Loadmore Button and kills the UI function of the Drag and Drop elements.
Drag N Drop:
<title>jQuery Dynamic Drag'n Drop</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.7.1.custom.min.js">
</script><script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse){
$("#contentRight").html(theResponse);
});
}
});
});
});
</script>
DND updateDB.php
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}?>
DND main PHP:
<ul>
<?php
$query = "SELECT * FROM records ORDER BY recordListingID ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<li id="recordsArray_<?php echo $row['recordID']; ?>"><?php echo $row['recordID'] . ". " . $row['recordText']; ?></li>
<?php } ?>
</ul>
Loadmore:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script>
$(function() {
var page = 1;
$("#LoadMore").click(function(){
$.ajax({
type:"GET",
url:"page4.php",
data:{page:page},
success: function(response) {
$("#data_grid").append(response);
page++;
}
});
});
});</script>
Loadmore page4.php
<?php
//set argument as your mysql server
$connect = mysql_connect("mysql_server","mysql_user","mysql_password");
mysql_select_db("database_name",$connect);
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
$limit = 25;
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM table2 limit $offset, $limit";
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
if($numRows>0) {
while($row = mysql_fetch_array($result)) {
//get field data and set to the following row
echo "<tr><td>field 1</td><td>field 2</td><td>field 3</td></tr>";
//edit row as you table data
}
} else {
echo "<tr><td colspan='3'> No more data </td></tr>";
}
exit;
?>
What am I missing? Can I fix this? Am I going to have to scrap the Jquery Drag N Drop? Is there an alternative that I should be using?
Background: A user will rate listed items in the order they deem fit. The total possible Items exceed 300,000 but the user will probably only utilize the first few hundred and the rest is used as a searchable database to add an odd item into the list. I can get the 2 codes in question to work separately but when I attempt the combination they create conflict.
Thank you for your time in assisting this project.
Look here
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript">
and
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
are same (jQuery file)
So use only one
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript">
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