Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2006-10-21
4
Medium Priority
?
771 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 53

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 53

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

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

Color can increase conversions, create feelings of warmth or even incite people to get behind a cause. If you want your website to really impact site visitors, then it is vital to consider the impact color has on them.
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
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…
Suggested Courses

705 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