Jump to content

Realtime Value When Selecting In Drowpdown Menu


Muiter

Recommended Posts

Hi, I'm new to this forum and to JavaScript.I have added some nice ones already to my website but I need one more and I can't find to modify. I hope someone here can help me.I have a MySQL database with 2 tables, one with numbers and one with names.When I select out of a dropdown menu a number I want in realtime the corresponding name. Is this possible?

Link to comment
Share on other sites

It sounds like you want to find an AJAX tutorial. The idea is to communicate with your server and receive a response, but without reloading your page. Because you're transferring very small chunks of data, it can be very close to realtime.

Link to comment
Share on other sites

It sounds like you want to find an AJAX tutorial. The idea is to communicate with your server and receive a response, but without reloading your page. Because you're transferring very small chunks of data, it can be very close to realtime.
Thank you got your reply. I have searched this week for a good tutorial and seems you're right. JAX is the wat to go.I founf this tutorial http://onlinehowto.net/Tutorials/AJAX/MySQ...with-AJAX/788/1 but I don't understand the 3rd and final page. Where do I place this code?
Link to comment
Share on other sites

That code is THE ENTIRE TEXT of ajax.php, the script that gets called by the AJAX function listed on page two.
That is what I thought but it's not working. I tried it with the same settings. I have build this databse to test:
CREATE TABLE IF NOT EXISTS `employ` (  `id` int(3) NOT NULL,  `name` varchar(255) NOT NULL,  `appoint_date` varchar(255) NOT NULL,  `country` varchar(255) NOT NULL,  `city` varchar(255) NOT NULL,  `email` varchar(255) NOT NULL,  `phone` varchar(255) NOT NULL

With the codes:index.php

<html> <head> <script language="JavaScript" type="text/javascript"> function display_data(id) {  	xmlhttp=GetXmlHttpObject(); 	if (xmlhttp==null) { 		alert ("Your browser does not support AJAX!"); 		return; 	}  	var url="ajax.php"; 	url=url+"?employ_id="+id; 	xmlhttp.onreadystatechange=function() { 		if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete") { 			document.getElementById('employ_data').innerHTML=xmlhttp.responseText; 		} 	} 	xmlhttp.open("GET",url,true); 	xmlhttp.send(null); } </script> </head> <body> <select onchange="display_data(this.value);"> 	<option>Select employ</option> 	<?php 	mysql_connect('xxxx','xxxx','xxxx'); 	mysql_select_db('xxxx'); 	$query="select id, name from employ order by name asc"; 	$result=mysql_query($query); 	while(list($id, $name)=mysql_fetch_row($result)) { 		echo "<option value=\"".$id."\">".$name."</option>"; 	} 	?> </select> <div id="employ_data"><div> </body> </html>

ajax.php

<?php if (is_numeric($_GET['employ_id'])) { 	mysql_connect('xxxx','xxxx','xxxx'); 	mysql_select_db('xxxx'); 	$query="select * from employ where id=$_GET[employ_id]"; 	$result=mysql_query($query); 	$employ=mysql_fetch_array($result); 	echo "<table border=\"1\"> 		<tr> 			<td>Name:</td> 			<td>".$employ[name]."</td> 		</tr> 		<tr> 			<td>Appoint Date:</td> 			<td>".$employ[appoint_date]."</td> 		</tr> 		<tr> 			<td>Country:</td> 			<td>".$employ[country]."</td> 		</tr> 		<tr> 			<td>City:</td> 			<td>".$employ[city]."</td> 		</tr> 		<tr> 			<td>E-mail:</td> 			<td>".$employ[email]."</td> 		</tr> 		<tr> 			<td>Phone:</td> 			<td>".$employ[phone]."</td> 		</tr> 	</table>"; } ?>

Index.php is working, I see and can select out of the dropdown menu but I can't see the results.

Link to comment
Share on other sites

Let's debug by testing the things most likely to be wrong.At the top of display_data(), add these lines (you can delete them later):alert(id);return;Reload and test it. If id comes up undefined, you have a problem. Older browsers won't support this, for example:<select onchange="display_data(this.value);">The old way is 100% reliable:<select onchange="display_data(this.options[this.selectedIndex].value);">If all that is working, put these lines at the top of ajax.php:echo "Hello";exit;Your goal here is simply to find out if you have basic communication. Good luck. Let me know what you learn.

Link to comment
Share on other sites

There is one error that shows up, I didn't see it before. Object expected

At the top of display_data(), add these lines (you can delete them later):alert(id);return;Reload and test it. If id comes up undefined, you have a problem.
Sorry I don;t understand what you mean
Older browsers won't support this, for example:<select onchange="display_data(this.value);">The old way is 100% reliable:<select onchange="display_data(this.options[this.selectedIndex].value);">
Same result (none)
If all that is working, put these lines at the top of ajax.php:echo "Hello";exit;
works when browsing to ajax.php but won't show up at index.php
Link to comment
Share on other sites

So the PHP is fine. Something is wrong in the script. I'm just checking the obvious here -- but you do have a GetXmlHttpObject() function in your script somewhere, right? The debugging lines would look like this:

function display_data(id) {	alert(id); // ADD THIS	return; // AND THIS	xmlhttp=GetXmlHttpObject();// everything else . . .

We just want to find out if id actually has a value.

Link to comment
Share on other sites

Where does this show up?
An icon on the bottem left of my browser when I have selected an option at the pulldown menu (line number 5)
Do you have a url I could try? You could message me if you don't want everyone else to see it.
Sorry, it's an intranet server at my workplace. You can't reach it.
Link to comment
Share on other sites

The new script creates a true function instead of an anonymous function for the readystate handler, but that shouldn't matter.It also checks for errors in http.status, which your code also should do, but that shouldn't have affected the results either.I notice that it uses the escape function on the user id. That is good practice, and I should have considered it, but I never stopped to wonder what characters are in your user ids. When you enter a url directly, the browser escapes any danger characters automatically. When you send a url through an http object, you have to handle that.Can you post a sample id? I guess it doesn't matter anymore, but it would be good for both of us to find out for sure.

Link to comment
Share on other sites

I suppose it could just be the = character. Well, glad you got it.
I am really thankfull for your time and effort is this :) Thanks a lot. One more question about the last tutorial that is working.In the original code you have to fill in the ID in an textfield with this code:
	<p>Enter customer ID number to retrieve information:</p> 	<p>Customer ID: <input type="text" id="txtCustomerId" value="" /></p> 	<p><input type="button" value="Get Customer Info" onclick="requestCustomerInfo()" /></p> 	<div id="divCustomerInfo"></div>

I have changed it to an pulldown menu with this code but when selecting I get the message that the ID doesn't exsists.

<select onchange="requestCustomerInfo()"> 	<option>Select employ</option> 	<?php 	mysql_connect(xxxx,xxxx,xxxx); 	mysql_select_db(xxxx'); 	$query="select CustomerId from Customers order by CustomerId asc"; 	$result=mysql_query($query); 	while(list($CustomerId)=mysql_fetch_row($result)) { 		echo "<option value=\"".$CustomerId."\">".$CustomerId."</option>"; 	} 	?>

Any ideas?

Link to comment
Share on other sites

Your original code passed the id as an argument: <select onchange="display_data(this.value);"> The new code does not: <select onchange="requestCustomerInfo()">I suppose requestCustomerInfo() gets the value through document.getElementById(). You could also, but your original display_data function would have to change. It would be simpler just to pass the argument as you originally did.

Link to comment
Share on other sites

Ok I have sorted some things out and the basic script is working. But how do I implement this in my php files?test.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> 	<title>Customer Account Information</title> 	<script type="text/javascript"> 		var url = "zoek_offerte_order.php?id="; // The server-side script 	   function handleHttpResponse() {			if (http.readyState == 4) { 			  if(http.status==200) { 				  var results=http.responseText; 			  document.getElementById('divCustomerInfo').innerHTML = results; 			  } 			  } 		} 				function requestCustomerInfo() {	  			var sId = document.getElementById("txtCustomerId").value; 			http.open("GET", url + escape(sId), true); 			http.onreadystatechange = handleHttpResponse; 			http.send(null); 		} function getHTTPObject() {   var xmlhttp;   if(window.XMLHttpRequest){ 	xmlhttp = new XMLHttpRequest();   }   else if (window.ActiveXObject){ 	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 	if (!xmlhttp){ 		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 	} 	}   return xmlhttp;   } var http = getHTTPObject(); // We create the HTTP Object </script> </head> <body> <select id="txtCustomerId" onchange="requestCustomerInfo()"> 	<option>Kies offertenummer</option> 	<?php 	mysql_connect(xxxxx,xxxx,xxxx); 	mysql_select_db(xxxxx); 	$query="select offerte from offertenummers order by offerte desc"; 	$result=mysql_query($query); 	while(list($CustomerId)=mysql_fetch_row($result)) { 		echo "<option value=\"".$CustomerId."\">".$CustomerId."</option>"; 	} 	?> </select> 	<div id="divCustomerInfo"></div> </body> </html>

zoek_offerte_order.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <?php 		//customer ID 	$sID = $_GET["id"]; 		//variable to hold customer info 	$sInfo = ""; 		//database information 	$sDBServer = "xxxxx"; 	$sDBName = "xxxx"; 	$sDBUsername = "xxxx"; 	$sDBPassword = "xxxx"; 	//create the SQL query string 	$sQuery = "Select o.offerte, o.klant_id, o.omschrijving, a.klantnaam	FROM	offertenummers AS o	INNER JOIN	adressen AS a	ON a.id = o.klant_id  	where offerte=".$sID; 			  	//make the database connection 	$oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword); 	@mysql_select_db($sDBName) or $sInfo = "Unable to open database"; 			if($sInfo == '') { 		if($oResult = mysql_query($sQuery) and mysql_num_rows($oResult) > 0) { 			$aValues = mysql_fetch_array($oResult,MYSQL_ASSOC); 			$sInfo = $aValues['klantnaam']."<br />".$aValues['omschrijving']."<br />".					  					 "<a href=\"mailto:".$aValues['E-mail']."\">".$aValues['E-mail']."</a>"; 		} else { 			$sInfo = "Offertenummer $sID bestaat niet."; 		} 	} 		mysql_close($oLink); ?> 		</head> <body> 	<div id="divInfoToReturn"> <?php echo $sInfo ?> </div> </body> </html>

I habe 2 questions,1st: why can't I remove the line

"<a href=\"mailto:".$aValues['E-mail']."\">".$aValues['E-mail']."</a>";

if I do an error comes up.2nd: how do I implement the code for the pulldown menu of test.php is this code:

<td class="dr"><select name="offerte_id"><?php  $sql = "select `offerte`, `offerte` from `offertenummers` ORDER BY `offertenummers`.`offerte` DESC";  $res = mysql_query($sql, $conn) or die(mysql_error());  while ($lp_row = mysql_fetch_assoc($res)){  $val = $lp_row["offerte"];  $caption = $lp_row["offerte"];  if ($row["offerte_id"] == $val) {$selstr = " selected"; } else {$selstr = ""; } ?><option value="<?php echo $val ?>"<?php echo $selstr ?>><?php echo $caption ?></option><?php } ?></select></td>

Link to comment
Share on other sites

1st: why can't I remove the line
"<a href=\"mailto:".$aValues['E-mail']."\">".$aValues['E-mail']."</a>";

if I do an error comes up.

Because the complete statement is this, and you're only removing half of it:
$sInfo = $aValues['klantnaam']."<br />".$aValues['omschrijving']."<br />".					  	"<a href=\"mailto:".$aValues['E-mail']."\">".$aValues['E-mail']."</a>";

Your second question confuses me. test.php already has a routine for creating the select element and all its options. The code at the bottom of your post is similar, but different. Is the first one not working? Do you want to replace the first one with the second one? If that is the case, then do it, and simply change the select tag to read like the first one: <select id="txtCustomerId" onchange="requestCustomerInfo()">Or maybe I really don't understand.

Link to comment
Share on other sites

My first question is solved by changing the code to

$sInfo = $aValues['klantnaam']."<br />".$aValues['omschrijving']."<br />";

Strange, my second problem is solved as well with the code you suggested. I tried this before but it didn't work, maybe an typing error.Thank a lot fo all your effort to help me.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...