Ajax search doesnt connect to database - javascript

Iam trying to make a live ajax search . When you put a word it automatically shows suggestions bellow just like w3schools. But for some reason my index file and my php doesnt exchange data value or my database doesnt connect for some reason.What i always get is "no country found". Can you check the code for errors?
this is the php file :
<?php
include_once('dbconnect.php');
$q = intval($_GET['q']);
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
?>
and this is my index.php file :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function showCountry(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","indexsearchquery.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input id="search-box" name="q" type="text" autocomplete="off" placeholder="Search country..." onchange="showCountry(this.value)" />
<input type='image' name='search' id="search-icon" value='Submit' src="search-icon.png" >
<p style="color:white;">Suggestions: <span id="txtHint" ></span></p>

Your country name will not in integer. but you convert it into intval change your php file to
include_once('dbconnect.php');
$q = $_GET['q']; //<-----remove intval
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}

it is important to know the content of the dbconnect.php file because it the one that contains database connection variables.
Check if your MySQL Server is up and that all variable are well set.

Related

Choosing a district by city problem with php

I try to make when you select the city, show the district of this city. I am adding my code to below. I made it on local and it has not any issue but whenever I add this on online it's show noting. It consists of 3 parts; First part is input area, second part is Javascript area and last part for connect to database and get date.
here's input area:
<form action="#institutions" method="post">
<p>Select City*</p>
<select class="institutionsSelect" name="cityinstitutions" id="orders-institutions" onchange="getDetaiinstitutions(this.value);">
</select>
<p>Select District </p>
<select class="institutionsSelect" name="districtinstitutions" id="order-details-institutions">
</select> <br>
<input type="submit" name="institutionsList" autocomplete="off" value="LİST OF INSTITUTIONS" class="btn btn-md btn-blue black-hover" >
</form>
Here's javascript area;
<script type="text/javascript">
function getOrdersinstitutions() {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-orders-institutions.php", true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option>Select City</option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].cityId + "'>";
html += response[a].cityName;
html += "</option>";
}
document.getElementById("orders-institutions").innerHTML = html;
}
};
}
function getDetailinstitutions(cityId) {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-order-detail-institutions.php?cityId=" + cityId, true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option></option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].districtId + "'>";
html += response[a].districtName;
html += "</option>";
}
document.getElementById("order-details-institutions").innerHTML = html;
}
};
}
getOrdersinstitutions();
And here's is datebase connection areas. There are 2 different page one call get-orders-institutions.php and other is get-order-detail-institutions.php
**get-orders-institutions.php **
<?php
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_city";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
and get-order-detail-institutions.php
<?php
$cityId = $_GET["cityId"];
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_district WHERE cityId='$cityId'";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
Here all i used codes.
As the first option, select city should be written, but it is an empty input line. Whenever i change datebase setting i mean when i write wrong username and password Select City appear.
By the way these codes work fine in local with exactly the same codes with the same database.
Here is online page
online input area
here is local
Local input area
Local input result
What i suppose to do for take same result in online like local?
thanks in advance
UPDATE: I find what's the problem but i dont know how can i fix it.
If more than 16 rows of data are loaded into the ys_city table, it gives an error like this
How can i fix it?

update php page using ajax using post requests reload the page?

I am trying to change the content of my php web page using ajax as below
the index.php page has input filed that call a function to executed on the button click but my problem is that the page is reload it
so i want to know what I am doing wrong??
Note that i am using the post requests to keep my data secure as w3schools.com recommended
inexd.php file code below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
var x = xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
The data.php file code below
<?php
alert("Hello! php start processing");
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
With the <input type="submit" value="Search"> your sending the form the "old" way to the server not with Ajax!
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNuminput">
<button type="button" onclick="sendForm()">Search</button>
</div>
</form>
<script>
function sendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Execudted when finished and everything its Okay
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "acc_data.php", true);
xmlhttp.send("accNum="+document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
}
</script>
Then in your data.php you do not need any html you just need to process the the data that you received by the ajax post request(Session is also not needed for that) . In the xmlhttp.responseText you are receiving your answer from the server when the request is finished.
<?php
$accountNumber = $_POST['accNum'];// set a good variable name
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8'); //setup connection
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); // throws an error on connection error
}
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:ACCNUM'; // sql stirng
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':ACCNUM', $accountNumber); // binds the parameter
oci_execute($stid); // executes the query
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>

Javascript output online usernames in HTML table

I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
$query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
$query->execute();
$query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
$query->execute();
}
function addOrRefresh($ID){
$query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
$count = $query->fetchColumn();
if($count == 0){
$query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
$query->bindParam(':ID', $ID);
$query->execute();
}
else{
$query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
removeRefresh();
$ID = $_GET['id'];
addOrRefresh($ID);
$query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
$query->execute();
$onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
$resultaat = "";
foreach($onlineUsers as $user){
$resultaat .= "<p>{$user['username']} <br></p>";
}
echo "$resultaat";
}
?>
You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
<?php
session_start();
$ID = $_SESSION['ID'];
if (isset($_POST['logout'])) {
session_destroy();
$query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
?>
<html>
<head>
<title>Stratego</title>
<Link href="../layout/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./js/HeartBeat.js"></script>
<script>
$(document).ready(function () {
heartbeat.setSpelerId( <?php echo $ID; ?> );
heartbeat.polling();
});
</script>
</head>
<body>
<form method='post' name='logout' action="../setup/logout.php">
<input type='submit' name='loggout' value='Log me out'>
</form>
Singleplayer
<div id="online-list">
</div>
</body>
<?php echo "<script>
function heartbeat(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById(\"online-list\").innerHTML = xhttp.responseText;
}
};
xhttp.open(\"GET\", \"./wachtruimterInterface.php?action=heartbeat&id=" . $ID . "\", true);
console.log('keeping in touch ༼つ ◕_◕ ༽つ');
xhttp.send();
}
setInterval(heartbeat, 1000);
</script>"; ?>
</html>
The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
$resultaat .= "<tr><td>{$user['username']} <br></td></tr>";
}
echo "<table>$resultaat</table>";
Just now, doesn't seem to work, any tips on how to progress?
I've fixed the issue;
$resultaat = "";
foreach($onlineUsers as $user){
$naam= $user['username']
$resultaat .= "<tr><td>$naam</td></tr>";
}
echo "<table border=1>$resultaat</table>";

Send multiple variable with PHP AJAX GET onclick of a button

I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.

How to use ajax auto complete to display values from a MySQL database when user types a letter

I am having problem with displaying the data from MySQL. I want that when I type a letter in the input field the values coming from the database will display the related values.
For example I type A, and it will show all the vales relating to that product. Below is my code - please provide your suggestions.
<!DOCTYPE>
<html>
<head>
<script type="text/javascript">
var hxmlhttp = false;
if(window.XMLHttpRequest){
//for newer browser except ie6
xmlhttp = new XMLHttpRequest();
}else{
//for ie6 and below
xmlhttp = new ActiveXObjectt("Microsoft.XMLHTTP");
}
function askGoogleSuggest(){
var input = document.getElementById("textField");
if(input.value){
getData("select.php?qu=" + input.value,"targetDiv");
}else{
var targetDiv = document.getElementById("targetDiv");
targetDiv.innerHTML = "<div></div>";
}
}
function getData(dataSource, divId){
if(xmlhttp){
var obj = document.getElementById(divId);
xmlhttp.open("GET",dataSource,true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
}
</script>
</head>
<h2>Langpayan Trademark</h2>
<form >
Search for <input type="text" id="textField"
name="textField" onkeyup = "askGoogleSuggest()">
</form>
<div id="targetDiv">
<p>it will display values</p>
<div></div>
</div>
</body>
select.php
<?php
$dbc = mysqli_connect('localhost','root','black98765','activity_8a')
OR die("Cannot connect to MySql: ". mysqli_connect_error());
$display = "SELECT bug.* , product.*, hardware.hardware_brand, software.software_name, solution.solution_name, bug_hardware.*
FROM bug
JOIN product ON bug.product_no = product.product_no
JOIN bug_hardware ON bug.bug_no = bug_hardware.bug_no
JOIN hardware ON hardware.hardware_no = bug_hardware.hardware_no
JOIN software ON software.software_no = bug_hardware.software_no
JOIN solution ON solution.bug_no = bug.bug_no
WHERE product_name like '%on%'";
$re = mysqli_query($dbc, $display);
if($re){
echo "<table border=1 id='table_form'>
<tr>
<th>Product Name </th>
<th>Name of Bug </th>
<th>Brand Name</th>
<th>Operating System</th>
<th>Solution</th>
<tr>";
while($row = mysqli_fetch_assoc($re)){
echo "<tr>";
echo "<td>".$row['product_name']."</td>";
echo "<td>".$row['bug_name']."</td>";
echo "<td>".$row['hardware_brand']."</td>";
echo "<td>".$row['software_name']."</td>";
echo "<td>".$row['solution_name']."</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "Cannot fetch data";
}
?>
The problem got solved in a dialogue:
The function getData missed the divId parameter when called inside the askGoogleSuggest function.
Also the line WHERE product_name like '%on%'"; had to be changed to WHERE product_name like '".$_GET['qu']."%'"; to behave as expected by OP

Categories