PHP, AJAX Unable to display values based on dropdownlist - php

My codes were taken from http://www.w3schools.com/php/php_ajax_database.asp, however i modified to better suit me, but it isn't working as it should be.
Afile.php
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getDescription.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<?php
$comCtrl = new company_controller();
$companyArray = $comCtrl->retrieveAllCompany();
foreach($companyArray as $com) {
echo "<option value ='".$com."' >".$com."</option>";
}//end foreach
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
getDescription.php
<?php
require_once('dbManager.php');
$q = intval($_GET['q']);
$dbMgr = new dbManager();
$conn = $dbMgr->getDBConnection();
$query = "select company_address from company where company_name = '$q'";
$result = mysql_query($query);
echo "<table border='1'>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['company_address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbMgr->closeDBConnection($conn);
?>
dbManager.php
<?php
//require('/config/config.php');
require(dirname(__FILE__) . '\..\config\config.php');
class dbManager{
function getDBConnection(){
// start connection
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$connect)
{
die( 'Could not connect: '.mysql_error() );
}
// Select the database
if(!mysql_select_db(DB_NAME))
{
die('The database - '. DB_NAME .' does not exist!');
}
return $connect;
}
function closeDBConnection($connect){
// close the connection
mysql_close($connect);
}
}
?>
I was expecting to have the same result as shown on the website.
Instead, when i first run the files, i would see a dropdownlist(ddl) with all the company values, and beneath that ddl is the text "person info will be listed here". When i click on the ddl, i was hoping for the company's address to be populated at the div place of the text, but instead another ddl appeared beneath the first ddl. So now i have a ddl on the first row, another ddl on the second row, and the same text "person info will be listed here". WHat am i missing?

I would recommend you to use mysqli_query() or PDO::query()
This is the required syntax for mysql_query()
mysql_query(query,$conn);
use:
$q = trim($_GET['q']);

Related

Dropdown fetches data from database, wanting to make another dropdown that will multiply that number

Through some help from w3school, I managed to create a dropdown for out database, which would fetch the data about a certain product fine. That function is doing great, but I want to add an option for users to decide the number of products they want. To assist with that I want a dropdown that simply multiplies the prices gotten from the first database, if that is possible.
The PHP is the following
<?php
$con = mysqli_connect('localhost','root2','1234','LSnet');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$con->query('SET CHARACTER SET utf8');
if(isset($_GET['q']))
$q = intval($_GET['q']);
mysqli_select_db($con,'LSnet');
$sql = "SELECT * FROM Produkter Where id = '".$q."'";
$result = mysqli_query($con,$sql)
or die("Error: ".mysqli_error($con));
echo "<table>
<tr>
<th>Pris</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['ProduktPris'] . ' DKK' . "</td>";
}
echo "</table>";
mysqli_close($con);
?>
and the HTML is the following
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../../prisdatabase.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<body>
<form>
<select class="pris" name="NetTyper" onchange="showUser(this.value)">
<option value="">Vælg Nettype</option>
<option value="1">KampNet</option>
<option value="2">TræningNet</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vælg Nettype her</b></div>
--
Added short overview of my table in the database.
--
The expected output from say option one would be 595 DKK, which I would like to have the option to multiply if one would need several

MySQL query result doesn't show using AJAX

I have a database called opera_house with a table called room that has a field room_name and a field capacity. I want to show the room_name 's that have a capacity larger than the one entered by the user.
The Available Room text disappears, but my code only shows the MySQL query if I echo it, but I'm not sure if it is reaching to search the database.
This is my script code:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function showRoom(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_events.php?q="+str,true);
xmlhttp.send();
}
}
This is my html:
<body>
<form>
<input type="text" name="room" onkeyup="showRoom(this.value)">
</form>
<br>
<div id="txtHint"><b>Available Room...</b></div>
</body>
This is my php:
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= '".$q."'";
echo $sql;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['room_name'] . "</td>";
}
?>
My php file is called ajax_events.php
And my dbconnect.php is one that I constantly use to connect to this database.
Would really appreciate some help!!
I propose an answer using jquery. You've embedded it in your question but you're not using it ...
Explanations : You call the following url ajax_events.php with the parameter "q" only if str is defined, otherwise it fills the selector txtHint with nothing.
AJAX
if (str != "") {
$.ajax({
type: 'GET',
url: 'ajax_events.php',
dataType: 'JSON',
data : {
q: str
}
}).done(function (data) {
$('#txtHint').text = data;
}).fail(function() {
alert('Fatal error');
})
} else {
$('#txtHint').text = '';
}
With this configuration, it is important to return result with echo json_encode in your server side code.
PHP
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection, "opera_house");
$sql = 'SELECT room_name FROM room WHERE capacity >= '.$q; // Some corrections
$result = mysqli_query($connection, $sql);
$return = '';
while($row = mysqli_fetch_array($result)) {
$return .= '<td>' . $row["room_name"] . '</td>';
}
echo json_encode($return); // Return Json to ajax
?>
While thinking of JS it's fine. I think the problems are in the php code. Try this one.
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= " . $q;
$result = mysqli_query($connection,$sql);
if (!$result) {
echo mysqli_error();
exit();
} // this is to do debugging. remove when you get it fixed
$ret = ""; //variable to hold return string
while($row = mysqli_fetch_array($result)) {
$ret .= "<td>" . $row['room_name'] . "</td>";
}
echo $ret;

DB Connection in html using php

I have a HTML page index2.html. In this page, I have a DIV which I am using to call a PHP page. The Php page has DB connection parameters, an SQL to fetch values from the DB.
However, when the PHP is called from the HTML, I am getting redirected to the PHP page. All I want is to use this stored procedure to get the data from the database.
HTML Code Snippet
</head>
<body>
<div id="background">
<div id="Layer0"><img src="images/Layer0.png"></div>
<div id="Layer2"><img src="images/Layer2.png"></div>
<div id="parceldeliveryservic"><img src="images/parceldeliveryservic.png"></div>
<div id="Layer10">
<form action="insert4.php" method="post">
<input type="image" src="images/Layer10.png"/>
</form>
</div>
The PHP Code Snippet:
<?php include("connect.php");
//$q = intval($_GET['q']);
try {
$proc_rate ='rtPreston';
$proc_price = 0.0;
$conn = new PDO("mysql:host=$servername;dbname=testdb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "GetPrice(?, ?)";
$sql = "Call GetPrice(:input, #output_price)";
$stmt = $conn->prepare($sql);
echo $proc_price;
$stmt->bindParam(':input',$proc_rate, PDO::PARAM_INT);
$stmt->execute();
$stmt->closeCursor();
$proc_price = $conn->query("SELECT #output_price AS output_price")->fetch(PDO::FETCH_ASSOC);
if ($proc_price) {
echo sprintf('Price for %s is %lf', $proc_rate, $proc_price['output_price']);
}
} catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
//$conn = null; ?>
can you please let me know what needs to be done to display the result in the calling HTML page?
Many thanks
HTML
<div onclick="callPHP();">Click me!</div>
Javascript
<script>
function callPHP() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// xmlhttp.responseText contains the result of the PHP
alert( xmlhttp.responseText );
}
};
// Call the PHP
xmlhttp.open("GET", "insert4.php", true);
xmlhttp.send();
}
</script>

AJAX not sending parameters over

I'll get straight to the point.
I have a a list which shows everyone in the db who has confirmed that they'll be attending a match. I want the list to change depending on what group is chosen from a select box.
Here's what I have so far: html & AJAX
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("attendYes").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("attendingYes").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","attending.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a group:</option>
<option value="CMA">CMA</option>
<option value="CM1">CM1</option>
<option value="CP2">CP2</option>
<option value="CBBC">CBBC</option>
</select>
</form>
<br>
<div id="attendYes"><b>Person info will be listed here...</b></div>
</body>
</html>
And here is the 'attending.php' page that the choice is meant to be sent to:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('-----','-----','-----','-----');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"handsomejack_co_forms");
$sql="SELECT * FROM stats WHERE activity='".$q."' AND attend='0' ORDER BY username ASC";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I have changed the sql from ".$q." to a defined choice - like CMA - and it worked, so I know the issue comes from sending q over.
Any ideas as to what could be the problem?
Cheers.
There are two three things i would suggest:
A.)
Change the id of the target div. as you have attendYes and you are using txtHint.
B.) # js
You can try sending the query in the .send() like below.
xmlhttp.open("GET","attending.php",true);
xmlhttp.send("q=" + encodeURIComponent(str));
C.) and # php:
You should not use intval() although i am not very good at php but as per documentation it is something else. so i suggest you to change this:
$q = intval($_GET['q']);
to this:
$q = $_GET['q'];
There's no element like document.getElementById("txtHint"). Update it with correct one:
document.getElementById("attendYes").innerHTML = xmlhttp.responseText;
Why don´t you use Jquerys $.ajax Method instead.
It´s easier to implement and it´s runing in all Major Browsers.

In php, mysql how to run a loop only if record exist

I have a php script which has series of calculations and FORM RELOADS based on user Selection/Inputs, I need to run these only IF a record ADDITION is done to the table and not on FORM RELOADS, how to run a loop with this condition.
my PARTIAL php script bill-detail.php:
HOPE THIS WOULD SUFFICE:
<html>
<head>
<title>Cash Bill Detail</title>
<script language="javascript">
function reload(form)
{
document.location.href = 'bill-detail.php'
}
function showecr(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","billecr.php?q1=" + str,false);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect("localhost","svga","a!##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("svga", $con);
$user = $_SESSION['user'];
//<!--------------VALIDATIONS ------------------->
echo "<form name='form1'>";
echo "ECR: <input type='text' size='10' maxlength='10' name='ecrn' onchange=\"showecr(this.value);\"><br>";
echo "Product Type";
echo "<select name='product' onchange=\"reload(this.form);\">>";
echo "<option value='Gas'>Gas</option>";
echo "<option value='Others'>Others</option>";
echo "</select>";
echo "</form>";
//---As per user inputs copying value to variables---------------------
$hdr=mysql_query("SELECT * FROM BILLHDR_draft WHERE usr='$user'");
$hdr2=mysql_fetch_assoc($hdr);
$numrows=mysql_num_rows($hdr);
if ($numrows>0)
{
$cust_code=$hdr2['Ac_code'];
$product=$hdr2['prod_desc'];
//--Searching BILL DETAILS TABLE as per the user inputs from BILL HEADER Table------
$recs=mysql_query("SELECT * FROM BILLDTLS WHERE Ac_code='$cust_code' AND Prod_desc='$product'");
while ($rec2=mysql_fetch_assoc($recs))
{
mysql_query("INSERT INTO DEMURAGE (DC_No, DC_date, Ac_code, Product_Desc) VALUES ('$rec2[dc]', '$rec2[dcdate]', '$rec2[accode]', '$rec2[product]'");
}
}
mysql_close($con);
?>
You can add a boolean variable before the loop that you can use to track on whether a record has been added already. The following code is largely concept being that you didn't provide much of an example of code yourself, but hopefully you get the idea.
// Set to false initially
$recordAdded = FALSE;
if( $num_rows > 0 && $recordAdded == FALSE )
{
// Code to execute
// Set value to to TRUE after initial successful execution
$recordAdded = TRUE;
}

Categories