Why isn't my AJAX loading onto my webpage? - php

I've set up JavaScript and AJAX that's supposed to fetch data from a database subject to a set of filters, and return a table of results that match those filters. I thought I had the code set up correctly, but when I submit the search filter form, the page reloads and nothing else happens. I can't work out where I'm going wrong!
connection.php is just a file containing my database details/username/password, and I know that's working correctly. I've scoured through for syntax errors and can't find any, so it must be something to do with the way I've written my code. However, I'm very new to all this so am really struggling to see what exactly I've done wrong. Any help would be hugely appreciated!
my javascript:
function showStock(search, genre, publisher, minyear, maxyear) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
xmlhttp.open("GET", "stock.php?search=" + search + "&genre=" + genre + "&publisher=" + publisher +
"&min-year=" + min - year + "&max-year=" + max - year, true);
xmlhttp.send();
}
}
my filter form:
<form id="filters">
<label> Search by Title:</label><br>
<input type="search" name="search">
<label>Genre:</label><br>
<select name='genre'>
<option value='All'> All </option>
<?php
function dropdownOptions($category) {
require('connection.php');
$sql = "SELECT DISTINCT ".$category." FROM stock";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row[$category] . "'>" . $row[$category] . "</option>";
}
}
dropdownOptions("genre");
?>
</select>
<label>Publisher:</label><br>
<select name="publisher">
<option value="all"> All</option>
<?php
dropdownOptions("publisher");
?>
</select>
<div class="year">
<label>Release Year:</label><br>
<input type="number" name="min-year" min="1970" max="2018">
<label> to </label>
<input type="number" name="max-year" min="1970" max="2018">
</div>
<div class="buttons">
<button type="submit" onclick="showStock(search, genre, publisher, min-year, max-year)">SEARCH</button>
<button type="reset">CLEAR</button>
</div>
</form>
my stock.php code:
<?php
require('connection.php');
$search = $_GET['search'];
$publisher = $_GET['publisher'];
$genre = $_GET['genre'];
$minyear = intval($_GET['min-year']);
$maxyear = intval($_GET['max-year']);
if ($search == "") {
$searchQ = "";
} else {
$searchQ = "AND CONTAINS(title, $title) ";
}
if ($genre == "all") {
$genreQ = "";
} else {
$genreQ = "AND genre = $genre ";
}
if ($publisher == "all") {
$publisherQ = "";
} else {
$publisherQ = "AND publisher = $publisher ";
}
if ($minyear == "" && $maxyear == "") {
$yearQ = "";
} else if ($minyear == "" && $maxyear != "") {
$yearQ = "AND release_date <= $maxyear ";
} else if($minyear != "" && $maxyear == "") {
$yearQ = "AND release_date >= $minyear ";
} else if ($minyear != "" && $maxyear != ""){
$yearQ = "AND release_date BETWEEN $minyear AND $maxyear ";
}
$sql = "SELECT * FROM stock WHERE id > 0".$searchQ.$genreQ.$publisherQ.$yearQ.";";
$result = $conn->query($sql);
echo "<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
<th>Genre</th>
<th>Price</th>
<th>Release Year</th>
<th>Stock Units</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['publisher'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['release_date'] . "</td>";
echo "<td>" . $row['stock_units'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I expected a table of relevant results to load on my webpage (hosted on my uni server here: https://students.emps.ex.ac.uk/admt201/webdev/stock-lookup.php), but instead all that happens is that my search parameters are added to the url of the original webpage and nothing new loads.

This is not an answer, but a long comment with multiple suggestions.
A problem of this nature is best attacked by breaking it down and confirming each part. Since PHP is notoriously difficult to troubleshoot (since if there is an error it doesn't generate any helpful message it just abends) I suggest you tackle the PHP side first.
So, make a copy of your stock.php file and replace the $_GET[] variable assignments with some hard-coded data. Then, make sure it outputs success messages (to ensure you are receiving the data you expected) and run that modified stock.php file as a stand-alone. You first need to confirm that the PHP is working, because if it isn't you can troubleshoot the javascript side till the cows come home and true happiness will continue to elude you.
Another troubleshooting methodology that is useful when troubleshooting PHP is to simply add a number of file writes throughout the file, like this:
$hF = fopen("__debug.log", "a");
//run a couple lines of code
fwrite($hF, "Got to here 01");
//run a few more lines of code
fwrite($hF, "Got to here 02");
//repeat...
Then, check the created __debug.log file and see if you got all of the expected file writes, or if the code died somewhere along the way. Otherwise, how would you know?
Note that there is an extension for Chrome called PHPConsole that allows you to output console messages to the browser, but it can be a bit tricky to get working off the start -- whereas the above fwrite() method is rock-solid-reliable and easily implemented.
Similarly, on the javascript side, salt your code with a bunch of console.log() statements to identify where the problems are manifesting.

Related

HTML select from mysql based on previous select

I am currently building a website. I want to implement a feature with 3 HTML select fields.
city
street
building
I was able to achieve full fetch of all distinct cities, streets and buildings. However, that is not exactly what I need, since they are all shuffled and you can't really see if a certain city has a certain street or not.
Here is the algorithm I have in mind:
Pre-requisite: All dropdowns besides city are disabled and are only enabled upon dropdown above selection.
Step 1: User selects city via dropdown
Step 2: All streets of that city are then fetched from MySQL into the street dropdown and it is now enabled.
Step 3: User selects street via dropdown
Step 4: All buildings of that street are then fetched from MySQL into the building dropdown and it is now enabled.
I am very new to website development, so please bear with me here and if possible - point me in the right direction.
My current implementation:
<select name="city">
<?php
if ($result = mysqli_query($conn, $queryCity)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>
<select name="street">
<?php
if ($result = mysqli_query($conn, $queryStreet)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>
<select name="building">
<?php
if ($result = mysqli_query($conn, $queryBuilding)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>
Your algorithm could work like that.
But you may need to reload the page or fetch the content with a asynchronous request (for example AJAX) if the user selected a city. You could pass the city as a GET- or POST-Parameter, and if that Parameter is set search for the streets and enable the dropdown, else just disable the dropwdown menu. The same applies for the buildings.
And please use Prepared Statements instead of normal queries when using a query with user input, you don't want to get visited by Little Bobby Tables ;)
I have found a solution to this and it is quite simple.
.js:
function getBuildings() {
let street = document.getElementById("street").value;
let ajax = new XMLHttpRequest();
let method = "POST";
let url = "get_buildings_of_street.php";
let asynchronous = true;
const obj = {};
obj.street = street;
ajax.open(method, url, asynchronous);
ajax.setRequestHeader("Content-type", "application/json");
ajax.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
let data = JSON.parse(this.responseText);
let html = "<select>";
html += "<option value='" + "-" + "'>" + "-" + "</option>";
for (let a = 0; a < data.length; a++) {
html += "<option value='" + data[a] + "'>";
html += data[a];
html += "</option>";
}
html += "</select>";
document.getElementById("building").innerHTML = html;
}
}
ajax.send(JSON.stringify(obj));
}

Made an AJAX script that is supposed to use GET to fetch data using my PHP file, not working

The code is supposed to fetch the query result and display it according to the number written in the text box, i tried (onkeydown and onkeyup) and both didn't work, i have no idea why it is not working and what is my mistake.
HTML code:
<script>
function showRoom(rid) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getRoomAJAX.php?q="+rid, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
</script>
<form>
<input type="text" name="rid" onkeydown="showRoom(this.value)">
</form>
<div id="txtHint">Room...</div>
getRoomAJAX.php code:
<?php
session_start();
ob_start();
$q = $_GET["q"];
$db = new Database();
$dbc = $db->getConnection();
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
$query = "SELECT * FROM indvProj_room WHERE rid = '".$q."'";
$result = mysqli_query($dbc, $query);
//start creating the table HTML
if ($result) {
echo "<table border='1' align='center' cellspacing = '2' cellpadding = '4' width='100%'>
<tr>
<th><b>Room ID</b></th>
<th><b>Room Description</b></th>
</tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<tr>";;
echo "<td>" . $_SESSION['adminRoomChoice'] = $row['rid'] . "</td>";
echo "<td>" . $row['roomDesc'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p class="error">Sorry, cannot find the room, are you sure of the entered Room ID?</p>';
echo '<p class = "error">' . mysqli_error($dbc) . '</p>';
}
?>
Does showRoom() get called at all? Put a console.log(rid); inside showRoom() to see if that is getting called and whether the value is being passed in correctly.
If you can determine that it's getting into the showRoom(), then follow the code down and into PHP to see where it's failing. Echo some sample text at the top of the PHP file with return; right below it. That will tell you if the error is in the XMLHttpRequest code or somewhere in the PHP file.
Normally, I don't pass any variables/params with onkeydown type of events. Usually, I call a method like this without params and then retrieve the value based on the element's id. See this answer for more detail on that: https://stackoverflow.com/a/54040431/3103434

Getting the drop-down menu selected item and using it in php

I have the following drop-down list that fetches a list coalitions from the database (this list is populated as expected)
<form style = "display: inline-block;" >
<select class="form-control" name ="coalition_select" onchange = "showCandidates(this.value)" method="GET">
<option id = "coalition_id" value="coalition">Coalitions</option>
<?php
include_once 'connection.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
}
?>
</select>
</form>
The problem begins here. Here I'm trying to first get the selected value (which is on of the coalitions) from the drop-down list and second use the value to display users with similar coalition attribute.
here is the script to get the value from the drop-down:
<script>
function showCandidates (str) {
if (str.length == "") {
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","includes/admin.users.list.inc.php?q="+str,true);
xmlhttp.send();
}
}
</script>
and here is the admin.users.list.inc.php file
<body>
<?php
$q = $_GET['q'];
$conn = mysqli_connect('localhost','root','','voting');
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
mysqli_select_db($conn,"osako_Voting");
$sql="SELECT * FROM candidates WHERE coalition = '".$q."'";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Coalition</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['coalition'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
The problem seem to be that I'm unable to set the variable $q so that it captures the selected value. right now as it is set it seems to capture the index instead of the value itself. How can this be correctly done? If it is of any help, I'm using this tutorial as a guideline
https://www.w3schools.com/php/php_ajax_database.asp
IN SUMMERY:
If we have a drop-down list that has been populated dynamically using php script. How can be get the selected value using ajax and use the said value in another php script.
Thanks
It seems the problem is in this row:
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
You're passing the select value to showCandidates(), to be passed via AJAX but you're setting the option value to be always static "coalition" and not the dynamic values you're fetching from DB.
Maybe you should change the row to
echo "<option value=\"" . $row['coalition'] . "\">" . $row['coalition'] . "</option>";
your not setting value to value attribute . your just setting constant string for all option values coalition
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"$row['coalition']\">" . $row['coalition'] . "</option>";
}
I know you have accepted an answer but i am puzzled as to this;
in your function you have this
document.getElementById("txtHint").innerHTML = "";
But you don't have any form element with the id "txtHint"
So what element is being sort with that ID?

Ajax refine search

I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<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","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+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.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!

retrieve data using Ajax and mysql

I'm trying to retrieve data from multiple table. So when the user clicks and select an item php file to retrieve the data from the corresponding table.
this is my first try on Ajax used w3 school code and trying to modify, I guess the way I'm using if condition is the problem? Before I try with the multiple table it worked.
My Script
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "Please Select type of users to view";
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","get_users.php?q="+str,true);
xmlhttp.send();
}
}
</script>
My Form
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
</select>
</form>
My PHP Page
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','X','X','X');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
if ($q='Admin')
{
$sql="SELECT * FROM admin";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
<th>Password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
else if ($q='Staff')
{
echo "This is from Database B
}
else
{
echo "This is from database C";
}
mysqli_close($con);
?>
You're using $q = intval($_GET['q']); with a string value for your assignments.
intval() "Get the integer value of a variable"
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
and using an assignment rather than a comparison for both if ($q='Admin') and else if ($q='Staff') both being strings, as opposed to integers in your options.
which should read as and with 2 equal signs if ($q=='2') and else if ($q=='1') in order to match your select's numerical value options.
Or, change them accordingly with your options to read as Staff and Admin (and Customers) in the values, while removing the intval() from the GET array; the choice is yours.
You also don't need mysqli_select_db($con); since you've declared your 4 parameters in your initial connection and would fail for another reason; technically you didn't select a database for it.
You're also missing a quote and semi-colon in (a parse syntax error)
echo "This is from Database B
which should read as
echo "This is from Database B";
Footnotes:
The page which I believe you based yourself on, seems to be http://www.w3schools.com/php/php_ajax_database.asp
If so, then I suggest you follow their example completely and modify it slowly to fit your needs. I myself have used that demo (in the distant past) before with success.
Their example uses a WHERE clause also.
$sql="SELECT * FROM user WHERE id = '".$q."'";
Edit: Just for the record, there is a missing brace for this condition:
if ($q='Admin')
{

Categories