Tuesday, December 3, 2013

Submit Search query & get Search result without refresh (AJAX)


In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
  1. Use Ajax to Post the data from your form to a php file;
  2. That file in background will query the database and obtain the results for the data that he as received;
  3. With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
  4. At last, you need to set some controlling stuff to let styles and document workflow run smoothly.

So, having said that, here's an working example:

We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!

 index.php
<script type="text/javascript">
      $(function() {
        $("#lets_search").bind('submit',function() {
          var value = $('#str').val();
           $.post('db_query.php',{value:value}, function(data){
             $("#search_results").html(data);
           });
           return false;
        });
      });
    </script>

  </head>

  <body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">

    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      HEADER
    </div>
    <div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
      <form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
        Search:<input type="text" name="str" id="str">
        <input type="submit" value="send" name="send" id="send">
      </form>
      <div id="search_results"></div>
    </div>
    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      FOOTER
    </div>

  </body>

</html>
 
db_query.php
 
<?php

define("HOST", "localhost");

// Database user
define("DBUSER", "username");

// Database password
define("PASS", "password");

// Database name
define("DB", "database_name");

// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');

############## Make the mysql connection ###########

$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);

$db = mysql_select_db(DB) or die(DB_MSG_ERROR);


$query = mysql_query("
  SELECT * 
  FROM persons 
  WHERE age='".$_POST['value']."'
");

echo '<table>';

while ($data = mysql_fetch_array($query)) {

  echo '
  <tr style="background-color:pink;">
    <td style="font-size:18px;">'.$data["name"].'</td>
    <td style="font-size:18px;">'.$data["age"].'</td>
  </tr>';

}

echo '</table>';

?> 


No comments:

Post a Comment