Hi i am using the html dropdown's onchange event using ajax
In the code i am using, should get the address column value when i change the
drop down.
but it is not working.What may have gone wrong?
here is the code
<html>
<head>
<script>
function showUser( str ) {
if ( str == "" ) {
document.getElementById("txtHint").innerHTML="";
return;
}
if ( window.XMLHttpRequest ) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState==4 && xmlhttp.status == 200 ) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
mysql_connect('localhost', 'tiger', 'tiger');
mysql_select_db('theaterdb');
$sql = "select theater_name from theater;";
$result = mysql_query($sql);
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
while ( $row = mysql_fetch_array( $result ) ) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>
</form>
<br>
<div id="txtHint"><b>Info</b></div>
</body>
</html>
Code for getuser.php
<?php
$q = $_GET["q"];
$con = mysqli_connect("localhost", "tiger", "tiger", "theaterdb");
if ( !$con ) {
die('Could not connect: ' . mysqli_error( $con ) );
}
mysqli_select_db( $con );
$sql = "SELECT address FROM theater WHERE theater_name = '".$q."'";
$result = mysqli_query( $con, $sql );
echo "<table border='1'>
<tr>
<th>Firstname</th>
</tr>";
while( $row = mysqli_fetch_array( $result ) ) {
echo "<tr>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Ok, I've tweaked your files slightly, you shouldn't be using mysql_ or the mysqli_ functions any more, just don't... And you certainly shouldn't be using mysql function in one file and mysqli functions in the other... I've switched them over to use PDO, you're script now isn't susceptible to SQL injection, and as far as I can tell it works just fine.
index.html
<html>
<head>
<script>
function showUser(str) {
if(str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT theater_name FROM theater;";
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>
</form>
<br>
<div id="txtHint"><b>Info</b></div>
</body>
</html>
getuser.php
<?php
$q = strtolower(trim($_GET["q"]));
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT address FROM theater WHERE LOWER(theater_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
$sth->execute();
echo "<table border='1'><tr><th>Firstname</th></tr>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbh = null;
I am unable to understand why have you connected with database in both of php files ?
I would suggest you to visit below link.
http://www.w3schools.com/php/php_ajax_database.asp
Related
I have a problem with this code.
I created a drop-down menu that directly takes the categories from the database. so far everything is ok.
When, however, I choose the type, it only displays the header of the table and not the records.
can you tell me why?
I think the problem is "q" but I do not know how to modify it becouse I tried to do the query without 'Where' and correctly displays the records.
<html>
<script>
var xmlhttp;
function mostraInfo(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="2.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
<form>
Seleziona Categoria:
<select name="users" onChange="mostraInfo(this.value)">
<option value="">Seleziona categoria:</option>
<?php
//Seleziono quelli che sono i dipendenti
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$query = "SELECT distinct tipologia FROM gruppi ORDER BY tipologia ASC";
$result = mysql_query($query);
while($riga = mysql_fetch_array($result)){
echo "<option value='$riga[nome_gruppo]'> $riga[tipologia] </option>";
}
?>
</select>
</form>
<br />
<div id="info"></div>
</html>
----- file 2(2.php)------
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
It seems your problem is the query,you are using double quotation inside single quote, Try this instead :
$sql="SELECT * FROM gruppi WHERE tipologia = '{$q}'" ;
From the code, you've provided, I don't see where is $q defined.
So I believe in the end your query looks like:
"SELECT * FROM gruppi WHERE tipologia = ''"
You can always dump something in order to check what's really going on by inserting temporary code like this:
var_dump($sql);exit;
Just don't forget to remove/comment it after debugging ;)
Solution:
You need to get "q" parameter from the GET request:
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
mysql_real_escape_string function is there to prevent some simple SQL injections. Please check this out http://php.net/manual/en/function.mysql-real-escape-string.php
But it would be better to use at least PDO class instead of outdated "mysql_" functions.
Complete code of 2.php with fix:
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
UPDATE 19/01/2017 - PROBLEM RESOLVED - Removed 'intval' on get request within get.php file and the value q is now capturing the correct data.
What i'm trying to achieve can be summed up in 2 points:
1.) A dropdown box which dynamically populates according to a MySql table
2.) Depending on whats chosen in the dropdown the textfield below will display a corresponding id via a SQL query.
I've been trying to follow W3Schools guide and modifying it accordingly to match my needs, but i'm getting stuck.
Here is what I currently have:
PHP -
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('core_log');
$sql = "SELECT local_authority FROM ons_code_tbl";
$result = mysql_query($sql);
echo "<tr>";
echo "<td> Local Authority: </td>";
echo "<td>";
echo "<select name='local_authority'onchange='showLocal_authority(this.value)'>";
echo '<option value=""></option>';
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['local_authority'] . "'>" . $row['local_authority'] . "</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
?>
Script -
<script>
function showLocal_authority(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","get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
get.php -
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','core_log');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$name = $row['ons_code'];
echo "<td>" . $q . "</td>";
mysqli_close($con);
?>
I did a test and simply echoed the value q to see what its outputting, it should be the value of whatever they pick in the dropdown, but instead its displaying 0?
In the screenshot below, it should display 'Amber Valley' with the correct ONS code pulled from the MySQL table.
If anyone can tell me why the value q is not storing 'Amber Valley' for example, that would be great, thanks!
Replace this line:
$q = intval($_GET['q']);
for
$q = $_GET['q'];
Then make a query with prepared statement, to avoid SQL Injection:
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "s", $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ons_code);
mysqli_stmt_fetch($stmt);
Just replace echo "<td>" . $q . "</td>"; for echo "<td>" . $ons_code . "</td>";
I do not know how will I display the position and names of the officers from year selected by the user.
Edit:
I used ajax now, but I'm still having a problem. When I click the combobox and select a year, the officers still don't show up. Only the table with the header Position and Name that shows up, but no data from my database under those columns.
getyear.php
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM officers WHERE year = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Position</th>
<th>Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['position'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
main.php
<form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql = "SELECT DISTINCT year FROM officers ORDER BY year DESC";
$result = mysql_query($sql);
/* assign an onchange event handler */
echo "<select name='year' onchange='showofficers(this.value)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] ."'>" . $row['year'];
}
echo "</select> <br>";
?>
<div id="txtHint">
</div>
</form>
<script>
/* event handler ~ no ajax function shown */
function showofficers(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","getyear.php?q="+str,true);
xmlhttp.send();
}
}
</script>
some pseudo-code o give you an idea of how you could achieve the desired goal.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql = "SELECT DISTINCT year FROM officers ORDER BY year DESC";
$result = mysql_query($sql);
/* assign an onchange event handler */
echo "<select name='year' onchange='showofficers(this.value)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] ."'>" . $row['year'];
}
echo "</select> <br>";
?>
<script>
/* event handler ~ no ajax function shown */
function showofficers( value ){
/*
use ajax to send a request that fetches the officers details
based upon the year selected. Preferred method=POST for ajax query
*/
alert( 'send '+value+' via ajax, build the sql query and use the ajax callback to generate the new html content' );
}
</script>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* Intercept and process ajax request */
/* the year is POSTed by ajax */
$year = $_POST['year'];
$sql='select * from table where year='.$year;
$res=$db->query( $sql );
if( $res ){
/* process recordset and send back response */
}
}
?>
So I am trying to have a website update state and city lists from a server.
My code for states seems to work fine, the problem I have is with updating the city list. I adapted an answer from here earlier, and it doesn't seem to work, although that is most likely my fault.
here is the state php code.
<?php
$con= mysqli_connect($host, $user, $pass, $database);
if($debug){
echo $host,$user,$pass,$database;
}
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$states = '';
$resultState = mysqli_query($con,"SELECT DISTINCT State FROM CitiesStates");
while($row = mysqli_fetch_array($resultState))
{
if($debug){
echo $row['State'];
}
$states .="<option>" . $row['State'] . "</option>";
}
$statesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
echo $statesDrop;
mysqli_close($con);
?>
so on selection it should call this function.
<script type="text/javascript">
function getCity(stateId)
{
var strURL="findCity.php?state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
which calls this php file.
$stateId=intval($_GET['state']);
$con= mysqli_connect($host, $user, $pass, $database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Cities = '';
$resultCity = mysqli_query($con,"SELECT City FROM CitiesStates WHERE State='$stateId'");
while($row = mysqli_fetch_array($resultCity))
{
if($debug){
echo $row['City'];
}
$Cities .="<option>" . $row['City'] . "</option>";
}
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities' onchange=''>
" . $Cities . "
</select>";
echo $citiesDrop;
mysqli_close($con);
?>
Additionally my getXMLhttp() function, since this seems to be the problem
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
I think it is due to this in findCity.php
$citiesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
It looks like you copied it from your state php code, but did not update it correctly. You php page is probably sending a req.status of 500, as $states is not defined. Try updating to -
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities'>
" . $Cities . "
</select>";
I have a page that is supposed to display some data fetched by AJAX from a database, but instead it displays an error message.
The page that shows the data:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
<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","getinfo.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("localhost","username","password");
mysql_select_db("databasename");
//$niftystocks=array();
$sq="SELECT TPNTCode FROM `niftystock`";
$r=mysql_query($sq);
$i=0;
while ($ro=mysql_fetch_array($r)) {
//array_push($niftystocks,$row['TPNTCode']);
$tpnt=$ro['TPNTCode'];
$sql="SELECT * FROM `nsepricequotes_latest` where TickerPlantCode = '$tpnt' ";
$rs=mysql_query($sql);
$row=mysql_fetch_array($rs);
if ($i == 0)
echo "--" . $row['DateTime'] . "--";
$sy=$row['Symbol'];
echo "<span id='txtHint'></span><a href='#'><span onmouseover='showUser()'>$sy</span>: " . $row['LastTradedPrice'] . " (" . $row['PercentChange'] . ")</a>";
if($row['PercentChange'] >= 0)
echo " <img src='http://mastertrade.in/master/ticker/images/arrow-up.gif' border='0' > | ";
else
echo " <img src='http://mastertrade.in/master/ticker/images/arrow-down.gif' border='0' > | ";
$i++;
}
?>
getinfo.php:
<?php
$q=$_GET['q'];
echo $q;
$con = mysql_connect('localhost', 'username', 'password');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$sql1="Select OpenPrice,HighPrice,LowPrice from nsepricequotes_latest WHERE Symbol like '".$q."' ";
while($row1= mysql_fetch_array($sql1)) {
$openprice=$row1['OpenPrice'];
$highprice=$row1['HighPrice'];
$lowprice=$row1['LowPrice'];
$tpnt=$row1['TickerPlantCode'];
}
$sql="SELECT * FROM 52wkhighlow WHERE nFTCode = '$tpnt'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$wkhigh=$row['BSE52WkHighVal'];
$wklow=$row['BSE52wlLowval'];
}
?>
<html>
<body>
<table>
<tr>
<td>Open Price</td><td><?php echo $openprice; ?></td>
<td>High Price</td><td><?php echo $highprice; ?></td>
<td>Low Price</td><td><?php echo $lowprice;?></td>
<td>52 Week High</td><td><?php echo $wkhigh;?></td>
<td>52 Week Low</td><td><?php echo $wklow;?></td>
</tr>
</table>
</body>
</html>
I'm getting this error:
-undefined Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mastertr/public_html/master/ticker/getinfo.php on line 11
because you didn't run your $sql1 query
set this :
$sql1="Select OpenPrice, HighPrice, LowPrice from nsepricequotes_latest
WHERE Symbol like '". mysql_real_escape_string($q)."' ";
$result_1 = mysql_query( $sql1 );
then start :
while( $row = mysql_fetch_array($result_1) )
instead of :
while( $row = mysql_fetch_array($sql1) )
You forgot to run mysql_query()
$sql1="Select OpenPrice,HighPrice,LowPrice from nsepricequotes_latest WHERE Symbol like '".$q."' ";
while($row1= mysql_fetch_array($sql1))
should be something like
$sql1="Select OpenPrice,HighPrice,LowPrice from nsepricequotes_latest WHERE Symbol like '".$q."' ";
$res = mysql_query($sql1);
while($row1= mysql_fetch_array($res))
In your mouseover there's the following:
showUser()
Note that undefined and "" is not the same.
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
The above doesn't work because str is undefined and not an empty string.
Either do this:
showUser("")
Or do this:
if (str == undefined)