Solved

Can I use JavaScript onSelect() and PHP to show info from mySQL database

Posted on 2006-10-21
4
748 Views
Last Modified: 2009-07-29
I want to have a list of retail outlets that are stored in mysql db to be displayed when the user selects their state from a drop down list. Still pretty new to the whole PHP, mySQL and JavaScript scene, so forgive any obvious errors. The bits and pieces I have are:

<?php
$query       = "SELECT retailer, address, city, state, zip, phone FROM retailstores WHERE state = ???";
$return = mysql_query($query);
?>

<form name="returnstores" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="state" onchange="getstores();">
<option value="AK">Alaska</option>
<option value="CT">Connecticut</option>
<option value="ME">Maine</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="NH">New Hampshire</option>
<option value="NY">New York</option>
<option value="PA">Pennsylvania</option>
<option value="VT">Vermont</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
</select>
</form>
<?php do { ?>
      <div class="container">
            <div class="header"><?php echo $row['retailer']; ?></div>
            <div class="header"><?php echo $row['address']; ?></div>
            <div class="header"><?php echo $row['city'] . ',&nbsp;' . $row['state'] . '&nbsp;' . $row['zip']; ?></div>
            <div class="header"><?php echo $row['phone']; ?></div>
      </div>
<?php } while ($row = mysql_fetch_array($return)); ?>

I know JavaScript is client side script and php is server side, so how would I make something like this work? The question, I don't think, is too difficult but slightly urgent.

Thanks!
Aus2Srq
0
Comment
Question by:Aus2Srq
  • 2
  • 2
4 Comments
 
LVL 50

Accepted Solution

by:
Ryan Chong earned 250 total points
ID: 17782894
You can try look for the $_REQUEST object in php when a form is posted or passed by url, more info:
http://www.php.net/manual/en/reserved.variables.php
http://my2.php.net/en/language.variables.predefined
http://my2.php.net/variables.external


>>I know JavaScript is client side script and php is server side, so how would I make something like this work?

If you don't want your page to be refreshed everything the "state" selection changed, you probably need AJAX. More info have a look at:
http://www.w3schools.com/ajax/ajax_xmlhttprequest.asp

and here is an example on how to implement AJAX on a web page:

test.php:

<html>
<head>
</head>
<script language="javascript">
     var refreshInterval = 5000; //5 seconds
     var roomArray = new Array();
     
     var timeinfo = "";
     function loadStatus(url) {
          window.status = "loading status.."
          xmlhttp=null
          if (window.XMLHttpRequest) {
               xmlhttp=new XMLHttpRequest();
          } else if (window.ActiveXObject) {
               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
          if (xmlhttp!=null) {
               xmlhttp.onreadystatechange=state_Change
               xmlhttp.open("GET",url,true)
               xmlhttp.send(null)
          } else {
               //alert("Your browser does not support XMLHTTP.")
          }
     }
     function state_Change() {
          if (xmlhttp.readyState==4) {
               if (xmlhttp.status==200) {
                    try {
                         rtntext=xmlhttp.responseText;
                         writeStatus(rtntext);                        
                         window.status = "";
                    } catch(e) { window.status = ""; }
               }
          }
     }
     
     function writeStatus(v) {
          document.getElementById("rtn").innerHTML = v;          
     }
     
     rnd.today=new Date();
     rnd.seed=rnd.today.getTime();
     
     function rnd() {
          rnd.seed = (rnd.seed*9301+49297) % 233280;
          return rnd.seed/(233280.0);
     }
     
     function rand(number) {
          return Math.ceil(rnd()*number);
     }


     function getProgressUpdate() {
          rkey = rand(999999999999);
         
          loadStatus('test2.php?rkey='+rkey);
          setTimeout("getProgressUpdate()",refreshInterval);
     }
     
</script>
<body onLoad="getProgressUpdate()">
Returned value:
<div id="rtn"></div>
<p><a href="#" onClick="rkey = rand(999999999999);loadStatus('test2.php?rkey='+rkey);return false;">Refresh now</a></p>
</body>
</html>

test2.php:

<?php

echo date('l dS \of F Y h:i:s A');

?>


What you need to do is probably amend the function writeStatus, so that it can write the info into the menu (drop down) element instead.

hope this helps
0
 

Author Comment

by:Aus2Srq
ID: 17783824
Per suggestion from ryan, using AJAX, this is how I would SELECT * FROM retailstores in ASP:
sql="SELECT * FROM retailstores WHERE CUSTOMERID=" sql=sql & request.querystring("q")

How would I get this same value in PHP?
$query       = 'SELECT retailer, address, city, state, zip, phone FROM retailstores WHERE state = "' . ??? WHAT HERE ??? . '"';


where this is my selectstate.js file:
function getStores(str)
      {
      xmlHttp=GetXmlHttpObject()
      if (xmlHttp==null)
            {
            alert ("Browser does not support HTTP Request.")
            return
            }
      var url="inc/getretailers.php"
      url=url+"?q="+str
      url=url+"&qid="+Math.random()
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET",url,true)
      xmlHttp.send(null)
      }


and here is my drop down:
<select name="state" onchange="getStores(this.value);">
<option value="AK">Alaska</option>
<option value="CT">Connecticut</option>
....
</form>
0
 
LVL 50

Expert Comment

by:Ryan Chong
ID: 17783836
try something like:

$query      = 'SELECT retailer, address, city, state, zip, phone FROM retailstores WHERE state = "' . $_REQUEST['yourParameter'] . '"';
0
 

Author Comment

by:Aus2Srq
ID: 17784190
Thanks ryan! It works great! This is the link I used: http://www.w3schools.com/ajax/ajax_database.asp and modified to fit php.



Here's my code if interested......
##### selectstate.js
...
function getStores(str)
      {
      xmlHttp=GetXmlHttpObject()
      if (xmlHttp==null)
            {
            alert ("Browser does not support HTTP Request. Update your browser to view.")
            return
            }
      var url="inc/getretailers.php"
      url=url+"?q="+str
      url=url+"&qid="+Math.random()
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET",url,true)
      xmlHttp.send(null)
      }

function stateChanged()
      {
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
            {
            document.getElementById("txtHint").innerHTML=xmlHttp.responseText
            }
      }
...


##### getretailers.php
<?php
$query       = 'SELECT * FROM retailstores WHERE state = "' . $_REQUEST['q'] . '"';
$return = mysql_query($query);
?>
<?php
echo '<table>';
while ($row = mysql_fetch_array($return))
      {
      echo '<tr>';
      echo '<td>' . $row['retailer'] . '</td><tr>';
      echo '<td>' . $row['address'] . '</td><tr>';
      echo '<td>' . $row['city'] . ',&nbsp;' . $row['state'] . '&nbsp;' . $row['zip'] . '</td><tr>';
      echo '<td>' . $row['phone'] . '</td><tr>';
      echo '<td><hr></td></tr>';
      }
echo '</table>';
 ?>

### my drop down box
<select name="state" onchange="getStores(this.value);">
<option value=""></option>
<option value="AK">Alaska</option>
<option value="CT">Connecticut</option>
<option value="ME">Maine</option>
...
</select>
<p><div id="txtHint">Select your state from above list</div>
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
There’s a good reason for why it’s called a homepage – it closely resembles that of a physical house and the only real difference is that it’s online. Your website’s homepage is where people come to visit you. It’s the family room of your website wh…
This video teaches users how to migrate an existing Wordpress website to a new domain.
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question