scriptygoddess

13 Feb, 2007

Store Locator using PHP and AJAX

Posted by: Jennifer In: PHP|Scripts

Well, this was fun! I just made a store locator for a client using PHP and AJAX! 😀

I was basically following the instructions from this page: SomeCoders.com (Retrieving database information with AJAX, PHP and MySQL)

Take a look…

Here's what the heart of the "user" page looks like.

At the top – before the HTML tag – I open a connection with the database:

<?php
$dbconnection = mysql_connect ("localhost", "mysqlusername", "mysqlpassword") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("mydatabase", $dbconnection) or die("Couldn't open database: ".mysql_error());
?>

Then inside the page…

<h1>Store Locator</h1>
<p>To locate a store, select a state from the list below.</p>
<form name="selectastore">
<?php
$result = mysql_query("SELECT DISTINCT state from storelocator order by state");
?>
<div class="row">
<div class="label">State:</div><div class="field"><select name="state" onchange="getcities(this.value)">
<option value="" selected="selected">Select a State...</option>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?=$row['state']; ?>"><?=$row['state']; ?></option>
<?php } ?>
</select></div>
</div>
<div id="cities" class="row">
</div>
<div id="stores" class="row">
</div>
</form>

I used the javascript from the example. There's probably a way to combine it into one function, but because I'm still sorting my way through this, I just duplicated the function to pull cities, and then pull store names…

This is the function to grab the list of cities… (I've removed the comments, please see their post for a more detailed explanation on how this function works.)

function getcities(state){
document.getElementById('stores').innerHTML = "";
/*
doing this in case someone changes their mind and wants to select a different state. When they do - any stores that are already listed will be cleared.
*/
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xmlhttp = new
ActiveXObject('Microsoft.XMLHTTP');
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
var file = 'getcities.php?state=';
xmlhttp.open('GET', file + state, true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
var content = xmlhttp.responseText;
if( content ){
document.getElementById('cities').innerHTML = content;
}
}
}
xmlhttp.send(null)
return;
;
}

This is the function (almost exact duplicate of the above) to grab the list of stores… This time, I'm passing in the selected city, and the selected state.

function getstores(city, state){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xmlhttp = new
ActiveXObject('Microsoft.XMLHTTP');
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open('GET', 'getstores.php?state=' + state + '&city=' + city, true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
var content = xmlhttp.responseText;
if( content ){
document.getElementById('stores').innerHTML = content;
}
}
}
xmlhttp.send(null)
return;
}

Now onto the PHP pages I'm calling with the javascript…

"getcities.php" will populate the storelocator page with another dropdown box of cities it pulls from the database. Here's what that looks like:

<?php
$dbconnection = mysql_connect ("localhost", "mysqlusername", "mysqlpassword") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("mydatabase", $dbconnection) or die("Couldn't open database: ".mysql_error());
$result = mysql_query("SELECT DISTINCT city from storelocator where `state`= '".$_GET['state']."' order by city");
echo "<div class=\"label\">City:</div><div class=\"field\"><select name=\"city\" onchange=\"getstores(this.value, document.selectastore.state.options[ document.selectastore.state.selectedIndex ].value)\">";
echo "<option selected=\"selected\" value=\"\" >Select a City...</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['city'] ."\">" . $row['city'] ."</option>";
}
echo"</select></div>";
?>

When you select a city, a second php script gets called… "getstores.php". This one grabs all the store data for the selected city and state and updates the page with the listing of stores…

<?php
$dbconnection = mysql_connect ("localhost", "mysqlusername", "mysqlpassword") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("mydatabase", $dbconnection) or die("Couldn't open database: ".mysql_error());
$result = mysql_query("SELECT * from storelocator where `city`='".urldecode($_GET['city'])."' AND `state`='".$_GET['state']."';");
while ($row = mysql_fetch_array($result)) {
echo "<p>";
if ($row['url'] != "") {
echo "<a href='".$row['url']."' target='_blank'>";
}
echo $row['store'];
if ($row['url'] != "") {
echo "</a>";
}
echo "<br>";
echo $row['address']."<br>";
if ($row['address2'] != "") {
echo $row['address2']."<br>";
}
echo $row['city'].", ".$row['state']." ".$row['zip'];
if ($row['phone'] != "") {
echo "<br>".$row['phone'];
}
echo "</p>";
}
?>

I haven't done much with AJAX, so if you see any issues, feel free to let me know and I'll update the post with the corrections…

If I get some free time (*cough*HA!*cough*) I'll try to package it all up into a downloadable .zip file – including the "admin" side which has the adding/editing/deleting store functionality.

5/26/2008 Update Since there's still some interest in this, here is a download for the store locator. It includes the sql to create the store locator table, the admin pages, etc. There's no "design" to the pages – and the "login" for the admin pages is pretty bare-bones.

19 Responses to "Store Locator using PHP and AJAX"

1 | Tech

June 20th, 2007 at 10:55 am

Avatar

I have used a lot of your code in my new script, thanks for all your help here.

2 | Jason Warriner

July 11th, 2007 at 9:35 am

Avatar

Hello… just curious if you made a WordPress plugin for this. That would be awesome. Thanks!

3 | Chad Taylor

October 1st, 2007 at 12:27 am

Avatar

I have used snippets of scripts on your site many times. I am glad you are around making contributtions for people like us.

4 | Michael

January 8th, 2008 at 12:01 pm

Avatar

This is great. I have yet to test it but it was just what I was
looking for. We needed a way when customers call to look up the
stores in their area by Zip code and hopefully this'll do the trick!

5 | sugarplum

March 17th, 2008 at 6:55 pm

Avatar

great script, thanks for sharing! i am quite new to php and ajax and was wondering how to adapt the script to get all three select boxes to appear on the page from the start, instead of each box appearing one after the other? your help would be much appreciated.

6 | sugarplum

March 19th, 2008 at 7:01 pm

Avatar

sorry to be a nuisance. can anyone help?

7 | Jennifer

March 19th, 2008 at 9:44 pm

Avatar

Well – I guess I just don't understand why you would want the select box to appear before you have the data to populate it. In the script the list of states are shown – but the list of cities can't be shown until you know for which state to show a list of cities… ?

8 | sugarplum

March 20th, 2008 at 1:22 pm

Avatar

Hi, thanks for your reply. I'd like the select boxes on the page even though they are empty, because I am using the script as a search form not a store locator, with continent>country>city select boxes. If I leave it as it is I get a big empty space in the form where the select boxes are meant to appear and it may mislead some visitors into thinking that they can only search by continent and not by city.

9 | Jennifer

March 20th, 2008 at 2:48 pm

Avatar

in the html – in between <div id="cities" class="row"> and </div>

add the following:
<div class="label">City:</div><div class="field"><select name="city"></select>

That will basically be replaced completely when it gets the city list… but it will serve as a placeholder until a state is selected…

Make sense?

10 | sugarplum

March 20th, 2008 at 3:43 pm

Avatar

Thanks. I tried that already but was hoping there was a better method. It will have to do for now. Many thanks for your help anyway.
For anyone else with the same problem, the bottom of "getcities.php" will also need to be changed to add the third select box. For example:
echo "City:";
echo "Select a City…";
echo"";
Thanks again for sharing this script with us! Much appreciated!

11 | sugarplum

March 20th, 2008 at 3:48 pm

Avatar

oops sorry, the tags disappeared after I posted the script above…
echo "City:";
echo "Select a City…";
echo"";
hopefully this will work..

12 | sugarplum

March 20th, 2008 at 3:51 pm

Avatar

maybe not…anyhow just copy and paste the php code for making an empty select box already given in getcities.php

13 | Jacqueline

May 13th, 2008 at 4:07 pm

Avatar

Hi Jennifer!

I know it's been a while since you wrote this post, but I was hoping if you could tell me if you have this script available to share or for sale. Also, if you have figured out how to integrate it into wordpress, I would REALLY appreciate finding out how you did it.

Thanks a million!!!

14 | Jennifer

May 26th, 2008 at 4:30 pm

Avatar

Updated the post to include the download.

15 | Alistair

March 26th, 2009 at 6:14 am

Avatar

Hi this is great for none programmers like me unfortunatly im in the UK is there a way i can change state to County and have the English counties instead of all US states? Thanks Alistair

16 | David

July 31st, 2009 at 5:57 am

Avatar

This script is really great. I want to use it for my clients site: http://robertgraham.us.mytempweb.com but they have stores all over the world. Are you available freelance to add a country selector to the script?

17 | Paul

August 6th, 2010 at 3:09 am

Avatar

Hi! Seems like a great bit of code! I'm going to try using it on a website for a sports store chain in Norway. How can I adjust this to be used outside USA? The best would be if I could replace your "State" with out "Fylke" (Norway is like one state divided into regions, "fylke"). Thanks!

18 | porky

November 11th, 2010 at 1:02 pm

Avatar

Nice code. Very helpfull and free. I used the AZ Store Locator before. http://www.php4script.com/store-locator-script/. Nice script too

19 | karthik

June 30th, 2011 at 3:53 am

Avatar

I install the script,It works,But when i select the state,it shows the city dropdown,But the city is not to be select,and the dropdown,i can't see the letters.

And one more thing,I cannot,delete the store lists,it shows some parse errors.

Parse error: syntax error, unexpected $end in D:\karthik\php prac\xampp\htdocs\storelocator2\storelocator\admindelete.php on line 74

And also i am not able to edit the store also,ot shows the code inside the text box.

I am new to code,can u plz help me.

Thanks
karthik

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements