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);
}
Related
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;
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.
I have one simple html form where the fields can be auto populated by entering ID. its working fine. but, if ID not found in database, it can only return null to the form fields. i was trying to display an error message (can be a pop-up window) saying ID not found! but i failed to do it. here is my code to echo info into the form field:
if (strlen($param) > 0) {
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
$agentname = $myrow["contactfullname"];
$agenttel = $myrow["contacttel"];
$agentsal = $myrow["contactsalutation"];
$agentid = $myrow["contactid"];
$textout .= $agentid . ", " . $agentname . ", " . $agenttel . ", " . $agentsal;
}
} else {
$textout = " , , ," . $param;
}
}
echo $textout;
here is my ajaxFunction:
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode==13 || (e.target||e.srcElement).value==''){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
}
Dont use mysql_* functions, use PDO or Mysqli instead.
take care about $param value
If your query should return 1 result, you can use LIMIT 1 , and also there is no need to use while.
change this :
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
to
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$escaped_param%' LIMIT 1");
if (mysql_num_rows($result) == 1) {
$myrow = mysql_fetch_array($result);
4. if you want to show a message on your ajax response, you can use json or .... as an simple example, return this string on error :
error|" , , ," . $param;
and to check if an error occured on your client :
var result = "error|anything";
if(result.substr(0,6) == 'error|')
{
alert('An error occured.');
}
else
{
//do what you need!
}
Edit :
function handleHttpResponse()
{
if (http.readyState == 4)
{
results = http.responseText;
if(results.substr(0,6) == 'error|')
{
alert('An error occured.');
}
else
{
results = results.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
try do this in your sql
LIKE '%" . $param . "%'
I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.
<script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
var msg = form.msgInput.value;
form.txtInput.value = "";
form.msgInput.value = "";
var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
This is send.php
$username = "babar";
$password = "k4541616";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
//die(var_export($_POST,TRUE));
$parent = $_POST['parent'];
$msg = $_POST['msg'];
$name = 'Akhtar Nutt';
//$parent2 = json_decode($parent);
$msg_ID = '2q7b2sfwwe';
//$msg2 = json_decode($msg);
$query = "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
('','$name','$msg','$msg_ID','$parent')";
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error())
;}
?>
Alter
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
to:
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
You're missing the argument separator & in your query string...
You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.
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.