Solved

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

Posted on 2006-10-21
4
740 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 49

Accepted Solution

by:
Ryan Chong earned 250 total points
Comment Utility
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
Comment Utility
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 49

Expert Comment

by:Ryan Chong
Comment Utility
try something like:

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

Author Comment

by:Aus2Srq
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Problem to be resolved in this article Currently, development of website and web application can be done without writing thousands of lines of programming code by hand. Description This can be done through by using a open source framework such …
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 …
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now