CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: PHP/mySQL AJAX

  1. #1
    Join Date
    Jul 2012
    Posts
    8

    PHP/mySQL AJAX

    Now I have a new task to accomplish. I want to load the results on the page without having to reload the page again using ajax. I'm new to ajax though. Below is what I have, when it submits, the page just reloads without any results.

    Also, if I put the form's action to search.php, this works, so it's the ajax not working right or something.

    JQuery at the top of the main PHP page with the form
    Code:
    <!-- JQuery Library Load -->  
    <script src="../js/jquery-1.7.2.min.js"></script>
    
    <script type="text/javascript">
    $(function() {
    
        $("#zip-search-button").click(function() {
            // getting the form values
            var zipString  = $("#thezip").val();
            var radiusString = $("#radius").val();
            
            // forming the queryString
            var data = 'search='+ zipString + radius;
            
            // if searchString is not empty
            if(searchString) {
                // ajax call
                $.ajax({
                    type: "POST",
                    url: "search.php",
                    data: data,
                    beforeSend: function(html) { // this happens before actual call
                        $("#results").html(''); 
                        $("#searchresults").show();
                        $(".word").html(searchString);
                   },
                   success: function(html){ // this happens after we get results
                        $("#results").show();
                        $("#results").append(html);
                  }
                });    
            }
            return false;
        });
    });
    </script>

    The form on the main PHP page.
    Code:
    <div id="pick-shop">
    	<form action="" method="post">
    		<div id="zip-dropdown">
    		 <select class="sexydropdown" name="radius" id="radius">
                <option value="5">Within 5 Miles From...</option>
                <option value="10">Within 10 Miles From...</option>
                <option value="15" selected>Within 15 Miles From...</option>
                <option value="20">Within 20 Miles From...</option>
                <option value="25">Within 25 Miles From...</option>
                <option value="30">Within 30 Miles From...</option>
            </select>
            </div>
            <div id="zip-container">
            <input type="text" name="zip" id="thezip" required="required" value="" placeholder="Enter Your Zip Code" />
            <input type="hidden" name="submitted" value="submitted" />
    		<input type="submit" value="Submit" id="zip-search-button" />
            </div>
    	</form>
    </div>
    
    
    <div id="searchresults">Search results for <span class="word"></span></div>
    <div id="results" class="update">
    </div>


    The php processing page (search.php)
    Code:
    <?php
    
    // Create page variables
    $r = NULL;
    $z = NULL;
    $shops = NULL;
    $Errors = NULL;
    
    // Establish DB connection
    mysql_connect ('localhost', 'admin', 'thepassword') or die(mysql_error());
    mysql_select_db ('database') or die(mysql_error());
    
    // Declare page functions
    function Dist ($lat_A, $long_A, $lat_B, $long_B) {
    
      $distance = sin(deg2rad($lat_A))
          * sin(deg2rad($lat_B))
          + cos(deg2rad($lat_A))
          * cos(deg2rad($lat_B))
          * cos(deg2rad($long_A - $long_B));
    
      $distance = (rad2deg(acos($distance))) * 69.09;
      return $distance;
    
    }
    
    ### Handle form if submitted
    if (isset ($_POST['submitted'])) {
    
      // Validate Zip code field
      if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) {
    
        $z = mysql_real_escape_string((int)$_POST['zip']);
    
        // Verify zip code exists
        $query = "SELECT lat, lon FROM locations WHERE zip = '$z'";
        $result = mysql_query ($query);
    
        if (mysql_num_rows ($result) == 1) {
          $zip = mysql_fetch_assoc ($result);
        } else {
          $Errors = '<p>The zip code you entered was not found!</p>';
        }
    
      }
    
      // Validate radius field
      if (isset ($_POST['radius']) && is_numeric ($_POST['radius'])) {
        $r = (int)$_POST['radius'];
      }
    
      // Proceed if no errors were found
      if ($r && $z) {
    
        // Retrieve coordinates of the shops
        $shops = array();
        $query = "SELECT name, address, dealerships.city, dealerships.state, locations.zip, phone, lat, lon
    	FROM dealerships
    	INNER JOIN locations
    	ON dealerships.zip = locations.zip" or die(mysql_error());
        $result = mysql_query ($query) or die(mysql_error());
    
        // Go through and check all shops
        while ($row = mysql_fetch_assoc ($result)) {
    
          // Separate closest shops
          $distance = Dist ($row['lat'], $row['lon'], $zip['lat'], $zip['lon']);
    
          // Check if shop is in radius
          if ($distance <= $r) {
    
            $shops[] = array (
              'name'      => $row['name'],
              'address'   => $row['address'],
              'state'     => $row['state'],
              'city'      => $row['city'],
              'zip'       => $row['zip'],
              'phone'     => $row['phone']
            );
    
          }
    
        }
    
      } else {
        $Errors = ($Errors) ? $Errors : '<p>Errors were found please try again!</p>';
      }
    
    }
    
    
    // Any PHP Database Errors -->
    echo ($Errors) ? $Errors : '';
    
    
    // Let's do this! Show Results, Baby! -->
    if (isset ($shops)) {
    
      if (!empty ($shops)) {
    
        echo '<p><strong>' . count ($shops) . ' results were found.</strong></p>';
        foreach ($shops as $value) {
    
          echo '<p><strong>' . $value['name'] . '</strong><br />';
          echo $value['address'] . '<br />';
          echo $value['city'] . ', ' . $value['state'] . ' ' . $value['zip'];
          echo '&nbsp;<a target="_blank" href="http://maps.google.com/maps?q=',
          $value['address'], ' ',
          $value['city'], ', ',
          $value['state'], ' ',
          $value['zip'],
          '">Map this location</a><br />';
          echo 'Phone: ' . $value['phone'];
          echo '</p>';
    
        }
    
      } else {
        echo '<p><strong>No results found</strong></p>';
      }
    
    }
    ?>

  2. #2
    Join Date
    May 2002
    Posts
    10,943

    Re: PHP/mySQL AJAX

    [ split thread ]
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured