passing search parameter through jquery

笑着哭i 提交于 2019-12-23 20:12:40

问题


i have a form in which if the user enters the search query, its parameter should be passed through jquery and after getting the results it should load the results in the div container. since i'm not very well-versed with jquery, how would i do this?

html:

    //currently the data is being displayed on pageload:
    $(document).ready(function() {
    $("#bquote").load("quotes_in.php")
   });  

   $(".bsearch")
    .keydown(function() {
    //pass the parameter to the php page

       //display in div #bquote

    });


 <!-- Begin Search -->
        <div id="search" style="display:none;">
                <input type="text" class="bsearch" name="search" value="Search" />
        </div>
<!-- End Search -->

php [using OOP]:

if (isset($_POST["search"])) 
{
    $quotes->searchQuotes();
}

php class:

  $search = $_POST['search'];

  $sql = "SELECT * FROM thquotes WHERE cQuotes LIKE '%"
  .  mysql_real_escape_string($search) ."%' ORDER BY idQuotes DESC";


  try {

  $query = $this->_db->prepare($sql);
  $query->execute();

  if(!$query->rowCount()==0)
  {
   while($row = $query->fetch())
    {
    echo $this->formatSearch($row);
}

回答1:


I would do in that way:

$(".bsearch").keydown(function() {
  //create post data
  var postData = { 
    "bsearch" : $(this).val(), 
    "anotherParam" : "anotherValue" 
  };

  //make the call
  $.ajax({
    type: "POST",
    url: "yourAjaxUrl.php",
    data: postData, //send it along with your call
    success: function(response){
      alert(response); //see what comes out
      //fill your div with the response
      $("#bquote").html(response);
    }
  });
});

EDIT:

For putting a loader you need to check this here:

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

And to show a loader image for example:

$("#loading").ajaxStart(function(){
   $(this).show();
});

And to hide it when ajax call is complete:

$("#loading").ajaxComplete(function(){
   $(this).hide();
 });



回答2:


If you want to go down the ajax route...

$(".bsearch").keydown(function() {

    // Get the current input value
    var value = $(this).val(); 

    //pass the parameter to the php page
    $.ajax({
       type: "POST",
       url: "some.php", // replace this with the right URL
       data: "bsearch=" + value,
       success: function(msg){
          $("#search").html(msg);
       }
    });         
});

Read up on jQuery.ajax() and if you turn that search box into a proper form, utilize jQuery.serialize()




回答3:


Instead of using $_POST, you can use $_GET or $_REQUEST like the following:

var searchString = $(".bsearch").val();
$("#bquote").load("path_to_php_file.php?search="+searchString);

Then, in PHP, replace

$_POST

...with

$_GET


来源:https://stackoverflow.com/questions/3339731/passing-search-parameter-through-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!