Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2006-10-21
4
Medium Priority
?
779 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 54

Accepted Solution

by:
Ryan Chong earned 1000 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 54

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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

CTAs encourage people to do something specific to show interest in your company, product or service. Keep reading to learn why CTAs should always be thought of as extremely important, albeit small, sections of websites.
Dramatic changes are revolutionizing how we build and use technology. Every company is automating, digitizing, and modernizing operations. We need a better, more connected way to work together as teams so we can harness the insights from our system…
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…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
Suggested Courses

773 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