So close, yet so far. There is a table that displays the status of trouble ticket's (submitted, open, closed), when the ID of a ticket is clicked, more info is displayed and a button is given to Open the ticket or Close it. The button has an onClick event that sends the AJAX to work, and the button works as far as updating the status of the ticket is concered. Howeever, upon update the in the display table that shows the Status should update as well, but does not.
Button:
if ($ticketarray['status'] == "0") {
// print option to open ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Open Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
if ($ticketarray['status'] == "1") {
// print option to close ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Close Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
Table:
echo "<td name=\"statusholder\" style=\"padding: 0px;margin: 0px;\" /><div style=\"font-color: ". $fontcolor .";font-weight: bold;background-color: ". $statuscolor .";text-align: center;width: 100%;height: 100%;visibility: visible;\" name=\"statusdiv\">". statusTranslator($tixarray['status']) ."</div></td>";
AJAX:
function statusChange(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 (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById('statusdiv').style.visibility = hidden;
document.getElementById('statusholder').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","statuschange.php?id="+str,true);
xmlhttp.send();
}
STATUSCHANGE.PHP:
<?
include("./header.php");
if (isset($_GET['id'])) {
// valid request, get current status
$currentstatus = mysql_query("SELECT status FROM `table` WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("Cannot get current ticket status ". mysql_error());
$currentarray = mysql_fetch_assoc($currentstatus) or die("cannot make array ". mysql_error());
if ($currentarray['status'] == "0") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='1' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #FFFF00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Open</div>";
}
if ($currentarray['status'] == "1") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='2' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #33CC00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Completed (Closed)</div>";
}
} else {
echo "nothing to do here";
}
?>
On this line
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
remove the
&& xmlhttp.status==200
and it should work fine :-)
Related
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!
Edit
I've changed my approach based on some research, and I'm getting a partial result.
Database:
+--------------------------------------------------+
| id | date | objet | contenu | lu |
+--------------------------------------------------+
| 1 | 2013-01-20 | msg1 | msg1_content | 0 |
| 2 | 2013-01-20 | msg2 | msg2_content | 0 |
| 3 | 2013-01-20 | msg3 | msg3_content | 0 |
+--------------------------------------------------+
Link:
View'
JS/AJAX:
function markAsRead(id)
{
$.ajax(
{
type: "GET",
url: 'php/messagerie.php',
data: "id=" + id, // appears as $_GET['id'] # ur backend side
success: function(data)
{
// data is ur summary
$('#contenu').html(data);
}
});
}
PHP (php/messagerie.php)
$q = intval($_GET['id']);
// connect to db (of course not shown here)
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM coq_messagerie WHERE id = '".$q."'";
$lu = mysqli_query($mysqli, "UPDATE ".DB_PREFIX."messagerie SET lu='1' WHERE id='$q' LIMIT 1");
$result = mysqli_query($con,$sql);
echo "<table border='1' width='100%'>
<tr>
<th>id</th>
<th>date</th>
<th>objet</th>
<th>contenu</th>
<th>lu</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['objet'] . "</td>";
echo "<td>" . $row['contenu'] . "</td>";
echo "<td>" . $row['lu'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
I'm currently only retrieving only the <th>'s and not information when I'm looking up for id 2 or 3, but am getting information for id 1. How can this be only partially working?
Introduction
In an attempt to show dynamic information on my page, I'm using a mix of a few bits and pieces of code which should collect data from a basic HTML link which parses and returns data on the current page. Of course, this seems very basic, but being my first AJAX script, I would greatly appreciate some help.
Code
HTML Link:
$output .= '<a onclick="markAsRead('.$message['id'].'); return false;">'.View.'</a>';
Note: The link collects the id field as expected.
JS/AJAX Code:
function markAsRead(str) {
console.log("starting");
if (str=="")
{
console.log("string empty");
document.getElementById("contenu").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()
{
console.log("on ready state change");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("contenu").innerHTML=xmlhttp.responseText;
}
else
{
console.log("seems to returning information");
var abc = "<h1>Huh.</h1>";
document.getElementById("contenu").innerHTML=abc;
}
}
xmlhttp.open("GET","php/messagerie.php?q="+str);
xmlhttp.send();
}
Note: The console.log('###_'+str) is used to see where the code crashes. All logged properly (105, 107, 109).
PHP (php/read.php)
// connect to db (of course not shown here)
$message = $GET["messageid"];
$lu = mysqli_query($mysqli, "UPDATE messages SET lu='1' WHERE id='$message' LIMIT 1");
if(!$lu)
{
echo "Update error";
exit;
}
else
{
$data = mysqli_query($mysqli, "SELECT * FROM messages WHERE id='$message' LIMIT 1");
while($row = mysqli_fetch_array($data))
{
echo $row["contenu"];
}
}
Note: $lu is updated, which makes me believe the problem is either in the while/echo area or in my AJAX return.
Current console logs
starting
on ready state change
seems to returning information
-> GET ***/php/messagerie.php?q=3
** params -> q 3 **
** empty response **
** empty HTML **
on ready state change
seems to returning information
on ready state change
Where am I going wrong?
$message = $GET["messageid"];
should be
$message = $_GET["messageid"];
Solution found! This updates the field value to mark message as read and shows the message in the proper div.
Solution
In the AJAX request, the missing parameter of true has been added with the query.
Complete code
AJAX
function markAsRead(str)
{
if (str=="")
{
document.getElementById("contenu").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("contenu").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/messagerie.php?q="+str,true); // added ",true"
xmlhttp.send();
}
PHP
$q = intval($_GET['q']);
$con = mysqli_connect('','','',''); // values hidden here for obvious reasons
mysql_set_charset('utf8',$con);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM messages WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
$update = mysqli_query($con, "UPDATE messages SET lu='1' WHERE id='$q'");
if(mysqli_num_rows($result) > 0)
{
echo "<table border='1'>
<tr>
<th>id</th>
<th>date</th>
<th>objet</th>
<th>contenu</th>
<th>lu</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['objet'] . "</td>";
echo "<td>" . $row['contenu'] . "</td>";
echo "<td>" . $row['lu'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_close($con);
I have a MYSQL table called orgs that has columns for name, city, zip, and state. I want an AJAX dropdown that populates another field on my page with the name of the cities when I select the name of the city from the dropdown. I currently have the dropdown for the city updating based on what state I have but when I try the call for the organizations name based on the city my code fails. Here's what I currently have.
AJAX to get the names of the cities:
function list(str)
{
if (str=="")
{
document.getElementById("list").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("list").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/list_org.php?q="+str,true);
xmlhttp.send();
}
AJAX to get the names of the organizations based on the cities:
function get_cities(str)
{
if (str=="")
{
document.getElementById("get_cities").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("get_cities").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
xmlhttp.send();
}
list_org.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$sql2="SELECT DISTINCT city FROM orgs WHERE state= '".$q."'";
$result2=mysqli_query($connection,$sql2);
if(!$result2){
die("Database query failed. " . mysqli_error($connection));
}
echo "<form>";
echo '<select name="get_cities" onchange="get_cities(this.value)">';
echo '<option value="">Select a city:</option>';
while($row2= mysqli_fetch_array($result2)){
echo '<option value="' . $row2['city']. '">'. $row2['city'].'</option>';
}
echo "</form>";
mysqli_close($connection);
?>
get_cities.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$q='CA';
$sql2="SELECT * FROM orgs WHERE state = '".$q."'";
$result=mysqli_query($connection,$sql2);
if(!$result){
die("Database query failed. " . mysqli_error($connection));
}
echo $q;
$link_address = '#';
echo '<div id="get_cities">';
while($row = mysqli_fetch_array($result))
{
echo "<ul>";
echo "<li><a href='".$link_address."' name='" . $row['id'] ."'>" . $row['name'] . "</a></li>";
echo "</ul>";
}
echo '</div>'
mysqli_close($connection);
?>
I thought the problem was probably that I was passing cities with whitespace in them (like "los angeles") but I've tried it with single name cities like "Buffalo" and nothing happens when I change my selection either. Any help would be greatly appreciated.
You are missing a </select> in list_org.php. Try to fix that one first, then escape your string.
Replace
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
to
xmlhttp.open("GET","../php/get_cities.php?q="+escape(str),true);
here is an example that if i enter id then it will retrieve data from database & print it within form fields. my database has only three column- id, name & number. here is my index.html file:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
return true;
</script>
</head>
<body>
<p>Please Enter Your Staff ID:</p>
<div><input onkeyup="if (event.keyCode == 13) showData(this.value); return false;" /></div>
<div id="ajax-content"></div>
</body>
</html>
and here is my showData.php file:
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("test_01", $con);
// Select all fields from your table
$sql="SELECT * FROM staffdetails WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "Staff Name:" . "<input type='text' value='" . $row['name'] . "'>";
echo "</br>";
echo "Contact No.:" . "<input type='text' value='" . $row['number'] . "'>";
}
// Close the connection
mysql_close($con);
?>
now what i'm trying to do is, display the data in a given form field rather than print data with the form field. that means, the name & number input field will be already in the form with the id field. when i'll enter id then it will pull back the data & display it in the given form field. anyone can help please? thanks!
There's a javascript error in your index.html page. The return true statment should be inside function brackets.
Also try adding document type and content type on top of index.html page to show text fields instead of printing it.
Hope this will help solving your problem.
Through some very much appreciated help from users of this site I've been able to put together a script that upon a radio button click will populate a table with user details.
I thought that I'd be able to adapt it even further, but, quite possibly because of my lack of experience, unfortunately I've come across another problem, hence why I've added a new post.
Pulling the data from a mySQL database I'm using the code below to create a list of dates with an associated radio button.
<html>
<head>
<script type="text/javascript">
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($userid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$userid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Then with the following code I want to populate a table with the associated 'findname' details for the radio button clicked.
<?php
$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I can get the first part of the script to work, i.e. the creation of the date list and radio buttons, but when I select the radio button, the table appears with the correct column heading, but I receive the following error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/2/d333603417/htdocs/development/getuser2.php on line 21 with line 21 being this line: while($row = mysql_fetch_array($sql)).
As I said earlier the other users that answered my first post were great, but I just wondered if someone could perhaps have a look at this please and let me know where I've gone wrong.
Updated Code
Form
<html>
<head>
<script type="text/javascript">
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.findid, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($findid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$findid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"></div>
</body>
</html>
PHP
<?php
//$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds";
$result = mysql_query($sql);
// This is helpful for debugging
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
while ($row = mysql_fetch_array($result))
not
while ($row = mysql_fetch_array($sql))
mysql_fetch_array accepts a mysql result object (which you get from the mysql_query function call), not a string
In $row = mysql_fetch_array($sql)
$sql is a string, you should use $result instead, which is a mysql_result object.