views:

533

answers:

4

Hi,

I want to submit search query form & get search result without redirecting/reloading/refreshing on the same page.

My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success"

I am newbie, help would be appreciated.

Thanks.

A: 

This is what AJAX is for. In jQuery (apologies if you're looking for a different library)

$("form#search").bind('submit',function() {
  $.post("search.php",this.serialize(),function(data) { 
    // Put the code to deal with the response data here
  });
  return false;
});
Jamie Wong
Well I am newbie, I dont even know basics. so can you elaborate on more?
MANnDAaR
since you are binding on submit, its a good idea to return false to prevent it from submitting anyways.
halkeye
http://visionmasterdesigns.com/tutorial-ajax-interface-menu-using-jqueryphp/
Dan Heberden
@halkeye Thanks. Fixed.
Jamie Wong
A: 

You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.

Try this for starters:

http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html

After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.

desau
Thanx desau for the suggestion
MANnDAaR
A: 

It's good if you can get some basics of Ajax before straight away going to the code. Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.

Suppose you have an html like this:

<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html> 

Now, your javascipr code will be like this:

<script type="text/javascript">
function loadByAjax()
{
     $.ajax({
          type: "POST",
          url: "yourserverpage.php",
          data: "searchkey=data_from_user_input",
          success: function(response_data){
          $('myDiv').html(response_data)
          }
          });
}
</script>

so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div. So your page is updated without full refresh.

Also, please understand that, i used jquery library here for the Ajax function.

Wind Chimez
A: 

In order to submit a form, collect the results from database and present then to the user without 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, have 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!

Here is the code:

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;

<html lang="pt" dir="ltr">

    <head>

        <title>Search And Show Without Refresh</title>

        <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
        <meta http-equiv="Content-Style-Type" content="text/css">

        <!-- JQUERY FROM GOOGLE API -->
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;

        <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");

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

$conn = mysql_connect(HOST, DBUSER, PASS) or  die('Could not connect !<br />Please contact the site\'s administrator.');

$db = mysql_select_db(DB) or  die('Could not connect to database !<br />Please contact the site\'s administrator.');


$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>';

?>

The controlling stuff depends from what you want, but use that code, place does two files in the same directory, and you should be fine!

Any problems or a more explanatory code, please let us know ;)

Zuul
Down vote on a tested example ?!?
Zuul
Thanks Zuul for your descriptive answer. It really helped me to understand AJAX role.
MANnDAaR
@manndaar, clad I could help! ;)
Zuul