2

I'm interested in having a search form on the left side of a webpage, and the main content being the rows returned from the database.

Example : www.kijiji.ca

What I want to avoid, is reloading the whole page. Kijiji is not a good example of this, updating the query or changing the results page, updates the entire browser window. Ideally when search parameters are changed, the container with the search results will update, and nothing else. This way the outside information is preserved, and page loading time is reduced.

Would an Iframe be ideal for this? Or perhaps Jquery/ajax can handle this somehow ??

Thanks for the advice.

Chris
  • 846
  • 6
  • 16
  • AJAX would be your first choice here. Open your dev tools / network panel and you'll see what happens on kijiji – m90 Sep 18 '13 at 18:18
  • This web site has some explication and example on how to build a single page application : http://addyosmani.com/blog/building-spas-jquerys-best-friends/ – Yan Brunet Sep 18 '13 at 18:19
  • A good example: "Ask Question" page of Stackoverflow – Falci Sep 18 '13 at 18:22

7 Answers7

0

You can achieve this easily with AJAX and without any (deprecated) frames.

Look at JQuery for example. It provides all you need to refresh/populate certain areas of your page, without the need to reload the whole page.

Try searching for jquery and ajax.

Andreas Gnyp
  • 1,500
  • 1
  • 19
  • 25
0

AJAX is your answer. It stands for Asynchronous Javascript and XML...depending on your development framework, requirements, skill/knowledge and a variety of other factors you'll be implementing it in a variety of fashions.

AJAX is not a language, it is a concept. The idea is to allow asynchronous updates to portions of (or whole) pages on a website/web application. Here's a few resources to start you off:

http://learn.jquery.com/ajax/

http://www.w3schools.com/ajax/

http://www.tutorialspoint.com/ajax/

With a bit more information on your choice of IDE and/or requirements (are you building an ASP/PHP application or a CMS-based website?) we can offer some more pointed help.

Mike H.
  • 1,731
  • 9
  • 31
  • It's a rails website with a page to search based on user-supplied parameters. After the search is complete, they'll want to filter/sort results – Chris Sep 18 '13 at 18:26
  • Ah ok well I'm not a rails guy but there's a ton on SO that are, you should add the tag. Nonetheless these resources will guide you down the right path. You'll likely need to build out both the client side JSON requests and the server-side logic in order to parse/interpret/act on the aforementioned. The clientside is fairly straightforward, some have posted quick examples as answers to your question already (and you'll find the same in all the links above). For the rails stuff you'll need some advice from those experienced with it. – Mike H. Sep 18 '13 at 18:29
0

I think you should go with JQuery ajax It's as simple as:

    var request = $.ajax({
      url: //here goes url,
      type: "GET",
      data: { param : value}, //pass your parameters here
      dataType: "html"
    });

    request.done(function( data ) {
      //here you update your main container
      $( "#main_container" ).html( data);
    });

    request.fail(function( jqXHR, textStatus ) {
      alert( "Request failed: " + textStatus );
    });
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • That's not "plain" Ajax, it's jQuery's Ajax implementation. Such differences should be made clear to a beginner, because against popular belief, jQuery and Javascript are different things. – Ingo Bürk Sep 18 '13 at 18:51
0

Further to what has been mentioned here about using AJAX, you'll need to have a server-side back-end that gets the required data from your db and uses a HTTP response to send data back to the client. This could be stored as JSON for instance and you can use that response to populate your search field.

I have python and wsgi set up on an apache server right now for a back-end for instance, but this sort of thing could be implemented through something like php as well.

0

Ajax is the best bet. try going through http://api.jquery.com/jQuery.ajax/ to learn more.

This is the basic template code:

            $.ajax({
                type: "GET",
                url: "",//type your url
                data: {
                    searchdata: searchdata
                },
                success: function (response) {
                   $('#Content').html(response); 
                }
            });

as you see if your content page has a div with id as Content. it would just update that div alone.

jero
  • 543
  • 3
  • 13
  • 30
0

You don't even need Ajax for this.

Here is some (admittedly sloppy) code from a recent project. Should get you started. You can add the Ajax later for neat stuff like a reset button, or chained select boxes. Good luck.

This code assumes your page is named index.php (the data is submitted to the same page) Also, the commented out echos are for testing your database connection and that the form data made it to your query. And you probably don't need this query, but there it is anyway. Make a fast test database and give it a try.

HTML:

<div id="formarea">
<form method="post" action="index.php">
Note: All fields are not required for searching<br>
First Name:
<input type="text" name="first"><br>
Last Name:
<input type="text" name="last"><br>
School:
<input type="text" name="edu"><br>
City:
<input type="text" name="cit"><br>
State:
<input type="text" name="st"><br>
<input class="submit" name="submit" type="submit" value="Find">
</form>
</div>

<div id="listarea">
 <?php 
mysql_connect('database', 'username', 'password') or die(mysql_error());
//echo "Connected to MySQL <br>";
mysql_select_db("hair1") or die(mysql_error());
//echo "Connected to Database <br>";
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$edu = mysql_real_escape_string($_POST['edu']);
$cit = mysql_real_escape_string($_POST['cit']);
$st = mysql_real_escape_string($_POST['st']); 


//echo $first; echo "<br>";
//echo $last; echo "<br>";
//echo $edu; echo "<br>";
//echo $cit; echo "<br>";
//echo $st; echo "<br>";
?>
<?php
if(isset($_POST['submit'])){

$query = "SELECT * FROM hair1 WHERE 1=1 ";
if($first) $query .= "AND fname=\"$first\" ";
if($last) $query .= "AND lname=\"$last\" ";
if($edu) $query .= "AND school=\"$edu\" ";
if($cit) $query .= "AND city=\"$cit\" ";
if($st) $query .= "AND state=\"$st\" ";


$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    echo "<div class='resultbox'><div class='infobox'>";
    echo $row['fname'];
    echo "</div><div class='infobox'>";
    echo $row['lname'];
    echo "</div><div class='infobox'>";
    echo $row['school'];
    echo "</div><div class='infobox'>";
    echo $row['city'];
    echo "</div><div class='infobox'>";
    echo $row['state'];
    echo "</div><div class='infobox'>";
    echo $row['phone'];
    echo "</div><div class='infobox'>";
    echo $row['email'];
    echo "</div></div>";
}
if ( mysql_num_rows( $result ) > 0 ){
}    

else{ echo "<p>Sorry, that search didn't turn up anything.  Please check your spelling and try again.</p>";
}}
else{ 
  echo  "<p>No Results Found</p>"; 
      } 
?>

</div>

CSS:

#formarea {
    height: 235px;
    width: 280px;
    float: left;
    clear: left;
    text-align: right;
    margin-right: 10px;
}
#listarea {
    height: 235px;
    width: 650px;
    overflow-x: hidden;
    overflow-y: auto;
    float: left;
}
.resultbox {
    height: 18px;
    width: 100%;
    padding-top: 3px;
}
.infobox {
    float: left;
    padding-right: 5px;
    padding-left: 5px;
}
Jason
  • 871
  • 1
  • 8
  • 18
0

As others have mentioned, AJAX is the best solution for what you requested.

Here is a full example that does what you want. Values in a database will be updated via AJAX, with a response appearing on the page without the page refreshing.

jsFiddle (all working except AJAX)

While jsFiddle cannot demonstrate the AJAX, you can see that in action if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database structure.

Two files are required:

One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript

HTML:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

        <style>
        </style>

        <script type="text/javascript">

            //Global var goes here:
            editRow = 0;

            $(document).ready(function() {
                $('#msgbox').dialog({
                    autoOpen:false,
                    width:400,
                    modal:true,
                    buttons: {
                        Submit: function() {
                            var mfn = $('#mfn').val();
                            var mln = $('#mln').val();
                            var mem = $('#mem').val();
                            $('table').find('tr').eq(editRow).find('.fname').val(mfn);
                            $('table').find('tr').eq(editRow).find('.lname').val(mln);
                            $('table').find('tr').eq(editRow).find('.email').val(mem);
            /*                
                            //Now do the ajax transfer to the server
                            $.ajax({
                                type: 'POST',
                                url: 'my_php_processor_file.php',
                                data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
                                success:function(recd){
                                    $('#alert').html(recd);
                                    $('#alert').dialog('open');
                                }
                            }); //END ajax code block
            */              //Now, close the dialog -- doesn't happen automatically!
                            $(this).dialog('close');
                        }, //END Submit button
                        Cancel: function() {
                            $(this).dialog('close');
                        } //END Cancel button
                    } //END all buttons
                }); //END msgbox div (dialog)

                $('.editbutt').click(function() {
                    editRow = $(this).parents('tr').index();
                    //alert(editRow);
                    var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
                    var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
                    var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
                    $('#mfn').val(fn);
                    $('#mln').val(ln);
                    $('#mem').val(em);
                    $('#msgbox').dialog('open');
                }); //END editbutt

                $('#alert').dialog({
                    autoOpen:false,
                    modal:true
                });
            }); //END document.ready

        </script>
    </head>
<body>

    <table id="tbl">
        <tr>
            <td>
                First Name
            </td>
            <td>
                Last Name
            </td>
            <td>
                Email
            </td>
        </tr>
        <tr>
            <td>
                <input type="text" class="fname" id="fn1">
            </td>
            <td>
                <input type="text" class="lname" id="ln1">
            </td>
            <td>
                <input type="text" class="email" id="em1">
            </td>
            <td>
                <input class="editbutt" type="button" value="Edit Row">
            </td>
        </tr>
        <tr id="tr2">
            <td id="td2a">
                <input type="text" class="fname" id="fn2">
            </td>
            <td id="td2b">
                <input type="text" class="lname" id="ln2">
            </td>
            <td id="td2c">
                <input type="text" class="email" id="em2">
            </td>
            <td id="td2d">
                <input class="editbutt" type="button" value="Edit Row">
            </td>
        </tr>
    </table>
    <div id="msgbox">
        <h2>Edit User</h2>
        First Name: <input id="mfn" type="text"><br/>
        Last Name : <input id="mln" type="text"><br/>
        Email Addy: <input id="mem" type="text"><br/>
    </div>
    <div id="alert"></div>

</body>
</html>

PHP Processor File: my_php_processor_file.php

<?php

    $fn = $_POST['first_name'];
    $ln = $_POST['last_name'];
    $em = $_POST['email_addy'];
    $uid = $_POST['user_id'];

/*
    //This is where you use the security features of PHP to strip_slashes, and
    //protect html_entities, etc. to guard your database against SQL injection
    //attacks, etc.  SEE THESE POSTS:
    https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
    http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
    http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/

    //Now, update the database:
    $success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");

    //Now, return a message or something
    if (mysql_affected_rows() == -1) {
        $output = '<h2>Sorry, database update failed</h2>';
     }else{
        $output = '<h2>Update successful</h2>';
    }

    echo $output;

Here are some other simple examples of how AJAX works:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111