Im looking to pass one variable from my PHP code to my Javascript code to validate a figure. I'm creating a shopping cart scenario whereby i have a variable 'in_stock' which specifies the amount of stock available for a product. If I enter an amount that is greater than the 'in_stock' available i need an error to be thrown. This is currently what I have:
Java Script
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable ="<?php echo $stock?>";
//To check if a non-numerical value is entered
if (isNaN(enteredChar))
{
alert("Not a Number!");
return false;
}
//To check if the input is empty
if (enteredChar=="")
{
alert("Empty!");
return false;
}
//To check if the amount entered is not greater than the amount in stock
if (enteredChar > stockavailable)
{
alert("Not enough in stock");
return false;
}
}
</script>
This is all occurring whilst my PHP has called the database and returned the value on the screen. As follows:
PHP
$product_id =(int)$_GET['product_id'];
$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$stock =$row['in_stock'];
$product_id = $row['product_id'];
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product_id;
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $row['product_name'];
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $stock;
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $row['unit_quantity'];
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $row['in_stock'];
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
}
echo "</table>";
echo "</form>";
mysql_close($dbhandle);
?>
add your stock value to a hidden input value stock_value
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart" ></input><Input type="hidden" id="stock_value" name="stock_value" value="'.trim($stock).'"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
in javascript
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable =document.getElementById('stock_value').value;
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!";
}
?>
With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.
$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount . "<br /><br />";
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert' .$message;
foreach($result as $val){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
Recording counts are done correctly, but I can not make the popup appear in any way.
try this. Hope this help you.
$sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount;
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert("'.$message.'")';
echo '</script>';
while($val=mysqli_fetch_assoc($result)){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye
$message = "Records found: " . $rowcount." \\n\t\\n\t";
if ($rowcount > 1) {
foreach($result as $val){
//var_dump($val);
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
$jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
echo $jvsVar;
}
I have a script. It work fine with against & exact match, but when I search with multiple keywords, it returns null and black page against my query.
Here is my code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo of Search Keyword using PHP and MySQL</title>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
MySQL Connection:
<?php
global $dbo;
$info['dbhost_name'] = "localhost";
$info['database'] = "search"; // database name
$info['username'] = "root"; // userid
$info['password'] = ""; // password
$dbConnString = "mysql:host=" . $info['dbhost_name'] . "; dbname=" . $info['database'];
$dbo = new PDO($dbConnString, $info['username'], $info['password']);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbo->errorInfo();
if($error[0] != "") {
echo "string";
}
?>
Result after query submitted:
$q = array(); // create an array
$sq = ""; // this variable will be used in the query
if(isset($_POST['txt_projectname']) && !empty($_POST['txt_projectname'])){
$projectname = mysqli_real_escape_string($conn,$_POST['txt_projectname']);
$q[] = "db_projectname='".$projectname."' ";
} // take the variable from input after submit and put it in the array
if(isset($_POST['txt_location']) && !empty($_POST['txt_location'])){
$location = mysqli_real_escape_string($conn,$_POST['txt_location']);
$q[] = "db_location='".$location."' ";
}
$first = true;
foreach($q as $qu){
if($first){
$sq .= " where ".$qu;
$first = false;
}else{
$sq .= " and ".$qu;
} // for loop to use where and and in the query
}
$sql=mysqli_query($conn,"select * from table {$sq} ")or die(mysqli_error($conn));
You can do something like this
So I have a user page in which I include several tables, one of which uses a pagination script that is handled by javascript (so that I dont have to refresh the page when looking through the pages) now I'm trying to include this on my user.php page but it doesnt seem to work, any help appreciated
User.php page
<?php require 'session.php';
require 'header.php';
require 'includes/database.php';
$userid = $_GET['id'];
$con = mysql_connect($servername, $username, $password);
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);
//CLIENT INFO TABLE
include 'user/clientinfo.php';
echo "<br>";
// XLRSTATS TABLE
include 'user/xlrstatsinfo.php';
echo "<br>";
//ALIAS TABLE
include 'user/aliases.php';
//IP TABLE
include 'user/ipaliases.php';
//PENALTY TABLE
include 'user/penalties.php';
//PENALTY TABLE
include 'user/userchatlog.php';
?>
userchatlog.php page
<?php
require '../session.php';
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<script type = "text/javascript" src = "../includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = '../includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="../images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
and my search_results.php
<!-- include style -->
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<?php
//open database
include '../../database.php';
//include our awesome pagination
//class (library)
include 'ps_pagination.php';
//connect to mysql server
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s ago'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
//query all data anyway you want
$sql = "SELECT * FROM chatlog WHERE msg NOT LIKE '%RADIO%' ORDER BY id DESC";
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $mysqli, $sql, 45, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = $rs->num_rows;
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Name</th>";
echo "<th>Message</th>";
echo "</tr>";
//looping through the records retrieved
while( $row = $rs->fetch_assoc() ){
$msg=$row['msg'];
$team=$row['client_team'];
$team = str_replace("42","<img src=images/green.png>",$team);
$team = str_replace("3","<img src=images/red.png>",$team);
$team = str_replace("2","<img src=images/blue.png>",$team);
$team = str_replace("1","<img src=images/grey.png>",$team);
$msg = str_replace("^0","</font><font color=black>",$msg);
$msg = str_replace("^1","</font><font color=red>",$msg);
$msg = str_replace("^2","</font><font color=lime>",$msg);
$msg = str_replace("^3","</font><font color=yellow>",$msg);
$msg = str_replace("^4","</font><font color=blue>",$msg);
$msg = str_replace("^5","</font><font color=aqua>",$msg);
$msg = str_replace("^6","</font><font color=#FF00FF>",$msg);
$msg = str_replace("^7","</font><font color=white>",$msg);
$msg = str_replace("^8","</font><font color=white>",$msg);
$msg = str_replace("^9","</font><font color=gray>",$msg);
$name=$row['client_name'];
$name=htmlentities($name);
$time=$row['msg_time'];
echo "<tr class='data-tr' align='center'>";
echo "<td align=center>";
echo _ago($time);
echo "</td>";
echo "<td align=center>";
echo $team;
echo "<a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td align=left> $msg </td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav' align='center'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
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>