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;
Related
I have a form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
I have two files, one that is html where I use ajax and one php file. When clicking on the button, nothing is being returned, I am not seeing any specific errors and I am sure that the value I put in are correct.
<script>
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
if(reservation_id)
{
var param = "?reservation_id=" + reservation_id + "&guest_last_name=" + guest_last_name;
var url = "test04.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
var guest_full_name = document.getElementById('guest_full_name');
var unit_number = document.getElementById('unit_number');
var floor = document.getElementById('floor');
var key_sa = document.getElementById('key_sa');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
guest_full_name.innerHTML = (!!result.guest_full_name) ? result.guest_full_name : '';
unit_number.innerHTML = (!!result.unit_number) ? result.unit_number : '';
floor.innerHTML = (!!result.floor) ? result.floor : '';
key_sa.innerHTML = (!!result.key_sa) ? result.key_sa : '';
}
}
}
}
</script>
<p id='employee_name'></p>
<p id='employee_age'></p>
<p id='safe_code'></p>
My test04.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name, guest_last_name unit_number, floor, key_sa FROM reservations2 INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg) INNER JOIN unit USING (unit_id) where reservation_id ='".$reservation_id."'AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query) or die(mysql_error());
$response = array();
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$response['guest_full_name'] = ($row['guest_full_name'] != '') ? $row['guest_full_name'] : '';
$response['unit_number'] = ($row['unit_number'] != '') ? $row['unit_number'] : '';
$response['floor'] = ($row['floor'] != '') ? $row['floor'] : '';
$response['key_sa'] = ($row['key_sa'] != '') ? $row['key_sa'] : '';
}
}
echo json_encode($response, true);
?>
I am not seeing any specific errors
Where are you looking?
Did you check the raw response from the PHP script or just look at what was rendered in your browser?
Did you verify that error logging is working and did you check your logs?
The logic of your PHP is unclear - your JSON data and the PHP array can't handle multiple records yet you process multiple records. It would be nice to implement REST properly. This should also apply authentication and use CSRF for security - but I'll assume you left those out for illustrative purposes.
Your code is not written to handle failures or missing data. Consider (noting all the differences with what you posted):
<?php
$conn = mysqli_connect("","","","");
$response = array();
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name
, guest_last_name unit_number, floor, key_sa
FROM reservations2
INNER JOIN guest
ON (reservations2.reservation_id=guest.reservation_idg)
INNER JOIN unit USING (unit_id)
WHERE reservation_id ='".$reservation_id."'
AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query);
if (!$result) {
$response['status']=503
$response['msg']="Error";
trigger_error(mysql_error());
finish($response);
exit;
}
$response['status']=200;
$response['msg']='OK';
$response['guest_full_name'] = htmlentities($_GET['guest_last_name']);
$response['reservations']=array();
while($row = mysqli_fetch_assoc($result)) {
$response['reservations'][]=array(
'unit_number'=>$row['unit_number'],
'floor'=>$row['floor'],
'key_sa'=>$row['floor_sa']);
}
}
finish($response);
exit;
function finish($response)
{
header("HTTP/1.1 $response[status] $response[msg]");
header("Content-type: application/json");
echo json_encode($response, true);
}
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
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']);
I am having an issue with my AJAX and MySQL/PHP script.
The first file below, is my javascript file I use to test accessing my server. This file works as far as I know and have tested.
Game = function() {};
var timer;
Game.EncodeURI = function (text) {
return encodeURIComponent(text);
}
Game.DecodeURI = function (text) {
return decodeURIComponent(text);
}
Game.AlterDiv = function(div,data) {
if (Game.ID(div)) {
Game.ID(div).innerHTML = data;
}
}
Game.ID = function(value) {
return document.getElementById(value);
}
Game.ServerRequest = function (url, data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
data = xmlhttp.responseText.split("|");
for (i = 0; i < data.length; i++){
var one = Game.DecodeURI(data[parseInt(i)]);
var two = Game.DecodeURI(data[parseInt(i) + 1]);
var three = Game.DecodeURI(data[parseInt(i) + 2]);
var four = Game.DecodeURI(data[parseInt(i) + 3]);
var five = Game.DecodeURI(data[parseInt(i) + 4]);
}
} else {
return false;
}
}
if (!data) {
data = "";
}
data = data.replace(/: /gi, "=");
data = data.replace(/:/gi, "=");
data = data.replace(/, /gi, "&");
data = data.replace(/,/gi, "&");
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Game.Action = function (id, seconds) {
clearTimeout(timer);
if (id) {
if (!seconds) {
Game.AlterDiv('message', 'You begin working.');
Game.ServerRequest("action.php", "id: " + id);
} else {
Game.AlterDiv('message', 'You begin working.');
Game.ID('timer').innerHTML = seconds;
if (seconds >= 2) {
seconds -= 1;
Game.ID('timer').innerHTML = seconds;
timer = setTimeout(function(){
Game.Action(id, seconds);
},1000);
} else {
Game.ID('timer').innerHTML = "Finished";
Game.ServerRequest("action.php", "id: " + id + ", x: x"); // Request it, then POST "x" to say timer has counted down.
}
}
} else {
alert("There was an error with your request.\n Please try again.");
}
}
This second file is a basic PHP web page that I use to test the said function.
<html>
<head>
<title>Test</title>
</head>
<body>
<span onClick="Game.Action('1','5');">Start Work</span><br /><br />
<div id="message"></div>
<div id="timer"></div>
</body>
</html>
<script type="text/javascript" src="game.js?<?php echo time(); ?>"></script><!-- the time() stops it cache-ing -->
This third file is my PHP/MYSQL file that I use to connect to the database.
<?php
$mysqli = new mysqli_connect("127.0.0.1", "root", "", "gurstang");
$id = $_POST['id'];
if(isset($_POST['x'])) {
$x = true;
}else{
$x = false;
}
$userid = 1;
$query = "SELECT * FROM `action_info` WHERE `actionid` = '$id'";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$action_name = $row['name'];
$basetimer = $row['time'];
$gaineditem = $row['itemid'];
}
$result->free();
}
$query = "SELECT `item`,`plural` FROM `items` WHERE `itemid` = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$gained_item = $row['item'];
$gained_plural = $row['plural'];
}
$result->free();
}
if($x == false){
echo "Action|$id|"5"";
$message = "You have begun working.";
echo "AlterDiv|message|$message";
}
if($x == true){
echo "Action|$id|"5"";
$itemnumber = mt_rand(1,2);
$gainedmessage = "You have gained $itemnumner $gained_item.";
echo "AlterDiv|message|$gainedmessage";
$query = "SELECT `count` FROM inventory WHERE userid = '$userid' AND itemid = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$count = $row['count'];
$add = $count + $itemnumber;
$updatequery = "UPDATE `inventory` SET `count` = '$add' WHERE `userid` = '$userid' AND `itemid` = '$gaineditem'";
$mysqli->query($updatequery);
}
}
else{
$insertquery = "INSERT INTO `inventory` (`userid`, `itemid` ,`count`) VALUES ('$userid', '$gaineditem', '1')";
$mysqli->query($insertquery);
}
}
?>
Those are all 3 of the file currently to run my script. I have an onclick event in the php webpage, and it sends the values to my Javascript function of Game.Action. After testing I have concluded or at least assume that my Javascript function for Game.Action works. After testing my Game.ServerRequest function, I have concluded that there is a change somewhere happening. Although, when I check my server to see if the updates actually happened, nothing happens. It doesn't update the timer div or the message div properly.
So basically my question is, is my issue with PHP/MYSQL or AJAX?
Thanks for your help.
As you see I have created drop down and give it name the field name, and I have also the count function.
What I want to do is, if some select drop down menu..show the how many result found in number like 10, 20,.. if the second dropdown selected it will check the two drop down selected and pass the result count..like that continuous..if you want to see example what exactly I want is go here and choose car the count will update..
http://en.comparis.ch/Carfinder/marktplatz/Search.aspx
I have the ajax and working well but I can't get the exact PHP code to count in live time.
AJAX Code..
var xmlHttp
function showCount(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="phpApplication.php";
url=url+"?action=count2";
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("countR").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP Code
function dropdown($field, $table)
{
//initialize variables
$oHTML = '';
$result = '';
//check to see if the field is passed correctly
if (($field == "")||($table == ""))
{
die("No column or table specified to create drop down from!");
}
$sql = "select distinct($field) from $table";
//call the db function and run the query
$result = $this->conn($sql);
//if no results are found to create a drop down return a textbox
if ((!$result) ||(mysql_num_rows($result)==0))
{
$oHTML .= "<input type='text' name='$field' value='' size='15'>";
}elseif (($result)&&(mysql_num_rows($result)>0)){
//build the select box out of the results
$oHTML .= "<select name='$field' onchange='showCount(this.value)'>\n<option value='all'>All</option>\n";
while ($rows = mysql_fetch_array($result))
{
$oHTML .= "<option value='".$rows[$field]."' name='".$rows[$field]."'>".$rows[$field]."</option>\n";
}
$oHTML .= "</select>\n";
}
//send the value back to the calling code
return $oHTML;
}//end function
function count1(){
$sql2 = "SELECT SQL_CALC_FOUND_ROWS * from produkt_finder_table where Bauform_d ='".($_POST['Bauform_d'])."' ";
$query = $this->conn($sql2);
$result = mysql_query( $query );
$count = mysql_result( mysql_query( 'SELECT FOUND_ROWS()' ), 0, 0 );
echo $count;
//$sql2 = "SELECT COUNT(Bauform_d) from produkt_finder_table where Bauform_d = 'mobil' ";
//echo var_dump($result1);
while($row = mysql_fetch_array($query))
{
// echo $row['COUNT(Bauform_d)'];
}
//echo mysql_num_rows($query);
// if (isset($_POST['Bauform_d']))
//{
/* if (mysql_num_rows($result)==0) {
echo '0';
} else {
echo mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $result;
echo $row['COUNT(Bauform_d)'];
// }
}*/
}
$action = $_GET['action'];
$proFin = new Application();
switch($action) {
case 'show':
$proFin->show_form();
break;
case 'search':
$proFin->search();
break;
case 'searchAll':
$proFin->searchAll();
break;
case 'count2':
$proFin->count1();
break;
}
What parts have you debugged?
Change the count1() function to just echo back the time or something using time().
Then if it returns the correct value you know your JS is working and your PHP script is calling the correct function.
I assume that the PHP code doesnt work as the SQL query is looking for $_POST['Bauform_d'] which isnt set when you call the xmlHTTP Request. Run a simple print_r($_POST); to make sure you are passing all the data you expect in the query. If it is not then change your JS code to pass the value - when you are sure your php script is being passed all the correct variables then begin to add back in your SQL query etc.
debug debug
Jacob's answer is the key.