How can i load database content via ajax before a filter keyup is pressed?

时间:2015-09-01 22:32:35

标签: javascript php jquery ajax

I have this codes below. It works when a filter parameter is presssed on keyup. but i need the content of the database to load via ajax as soon as the page is ready even when no filter search is initiated. here are my codes

jquery

<script type="text/javascript">
       $(document).ready(function(){
           $('.autosuggest').keyup(function() {

               var search_term = $(this).attr('value');
                 $.post('actionSessionsearch.php', {search_term: search_term}, function(data){
                         $('.divDisplay').html(data);
                     });
               });

           });

   </script>

php

<?php
include_once('../includes/dc_conect.php');

if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
     echo "hoho";
}
else
{    $search_term=$_POST['search_term'];

        $sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
        $resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
        $dbfieldSession=mysql_fetch_assoc($resultSession);
        $countSession=mysql_num_rows($resultSession);
        do{
            echo $dbfieldSession['session_name'].'<br>';
        }while($dbfieldSession=mysql_fetch_assoc($resultSession));

}
?>

it only retireves when i enter a value into the search box. I want to have my database details display even when the filter has not been initiated!

1 个答案:

答案 0 :(得分:0)

You could do following things:

PHP

if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
 /* Load data from Database here, something like SELECT * FROM sessions;*/
}
else
{    $search_term=$_POST['search_term'];

    $sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
    $resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
    $dbfieldSession=mysql_fetch_assoc($resultSession);
    $countSession=mysql_num_rows($resultSession);
    do{
        echo $dbfieldSession['session_name'].'<br>';
    }while($dbfieldSession=mysql_fetch_assoc($resultSession));

}

JS

Call your AJAX function inside $(document).ready(function(){...}) and use $.get instead of $.post