Solved

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

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

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
logo disappears on cell phones 5 56
Remove right text widget from smaller screens 15 93
Hovering effect 9 47
How search webpage "viewable text" only 1 61
An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
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.

912 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

19 Experts available now in Live!

Get 1:1 Help Now