douguai6716 2015-07-27 08:45
浏览 79

Ajax搜索和分页

I have this AJAX pagination code.

 $('document').ready(function() {
    $("#pagination a").trigger('click'); // When page is loaded we trigger a click

});

    $('#pagination, #searchButton').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
        e.preventDefault();
        var page = this.id; // Page number is the id of the 'a' element
        var pagination = ''; // Init pagination     


        $('#articleArea').html('<img src="images/ajax-loader.gif" alt="" />'); // Display a processing icon
        var data = {term: term, page: page, per_page: 9}; // Create JSON which will be sent via Ajax
        // We set up the per_page var at 4. You may change to any number you need.

        $.ajax({ // jQuery Ajax
            type: 'POST',
            url: 'includes/fetch-pages.php', // URL to the PHP file which will insert new value in the database
            data: data, // We send the data string
            dataType: 'json', // Json format
            timeout: 3000,
            success: function(data) {


                $('#articleArea').html(data.articleList); // We update the page with the event list
                console.log(data.num);


                // Pagination system
                if (page == 1) pagination += '<div class="cell_disabled"><span>Primero</span></div><div class="cell_disabled"><span>Anterior</span></div>';
                else pagination += '<div class="cell"><a href="#" id="1">Primero</a></div><div class="cell"><a href="#" id="' + (page - 1) + '">Anterior</span></a></div>';

                for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
                    if (i >= 1 && i <= data.numPage) {
                        pagination += '<div';
                        if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
                        else pagination += ' class="cell"><a href="#" id="' + i + '">' + i + '</a>';
                        pagination += '</div>';
                    }
                }

                if (page == data.numPage) pagination += '<div class="cell_disabled"><span>Siguiente</span></div><div class="cell_disabled"><span>Último</span></div>';
                else pagination += '<div class="cell"><a href="#" id="' + (parseInt(page) + 1) + '">Siguiente</a></div><div class="cell"><a href="#" id="' + data.numPage + '">Último</span></a></div>';

                $('#pagination').html(pagination); // We update the pagination DIV
            },
            error: function() {
            }
        });
        return false;
    });

Now I want to add a search form:

<form class="form-inline col-xs-12 col-sm-5 col-md-4 hidden-xs" id="searchFormTop">
          <div class="row buscar">
              <div class="form-group col-xs-9">
                <input type="text" placeholder="" class="form-control" name="searchTerm" id="searchTerm" value="test">
              </div>                
              <button type= "submit" class="btn col-xs-3" id="searchButton"> BUSCAR </button>
          </div>
        </form>

How can I get the value from the form and pass it to the AJAX call? I'm trying to add another event to trigger the ajax call when the form in submited and then get the search term value using val(), but I cannot make in work.

$('document').ready(function() {
    $("#pagination a").trigger('click'); // When page is loaded we trigger a click
});

$('#pagination, #searchFormTop').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
    e.preventDefault();
    var page = this.id; // Page number is the id of the 'a' element
    var pagination = ''; // Init pagination     
    var term = $('#searchTerm').val();

The PHP code processing the request is:

    $page = $_POST['page']; // Current page number
    $per_page = $_POST['per_page']; // Articles per page
    if ($page != 1) $start = ($page-1) * $per_page;
    else $start=0;
    $today = date('Y-m-d');

    $term = $_POST['searchTerm']; // Current page number


  // Select items list from $start. 
  // An item might have multiple categories. A regular join query will create a row for each category
  //so that the event will be displayed as many times as categories it has.
  //To group all the caegories in one single result, we can use GROUP_CONCAT and then, GROUP BY
  $sql = "SELECT *, events.name AS event_name,              --  THIS WILL the defferesnt categories on on eevent 
                       GROUP_CONCAT(DISTINCT catevent.cat_id) as cats,
                       GROUP_CONCAT(DISTINCT categories.name SEPARATOR ', ') as cat_names
                      FROM events                
           LEFT JOIN catevent
              ON catevent.event_id=events.event_id
           LEFT JOIN categories 
              ON catevent.cat_id=categories.id
           LEFT JOIN images 
              ON images.item_id=events.event_id 

           WHERE categories.parent_cat != 0
              AND publish=1 AND images.item_type_id=1 AND images.img_name NOT LIKE '%sm%' -- We want to get only the name of the regular img for each event 
              AND final_date >= '$today'
            GROUP BY events.event_id -- Needed to display all the events 
            ORDER BY events.initial_date ASC, events.initial_date DESC, events.name ASC
            LIMIT $start, $per_page";

  $select=$pdo->query($sql);
  $select->setFetchMode(PDO::FETCH_OBJ);
  $results = $select->fetchAll();




  // Total number of articles in the database
    $numArticles = $pdo->query("SELECT count(event_id) FROM events  WHERE publish=1 AND final_date >= '$today'")->fetch(PDO::FETCH_NUM); 

    $numPage = ceil($numArticles[0] / $per_page); // Total number of page

    // We build the article list
    $articleList = '';
    foreach( $results as $result) {

        //Get final month, year, and day from date stored in db
    $date_from_db=test_output($result->final_date);
        $time=strtotime($date_from_db);
        $year= date('Y', $time);
        $year_short= substr($year,2);
        $month=date('n', $time);
        $day=date('j', $time);

        //Get initial month, year, and day from date stored in db
    $date_from_db_i=test_output($result->initial_date);
        $time_i=strtotime($date_from_db_i);
        $year_i= date('Y', $time_i);
        $year_short_i= substr($year_i,2);
        $month_i=date('n', $time_i);
        $day_i=date('j', $time_i);  



        //get the sm image name
        $lg_image=test_output($result->img_name);
        $images_names=get_img_names($lg_image);
        $img_sm= $images_names['regular_sm'];  


        //default event slug
            $event_slug=test_output($result->slug);
            if (empty($result->slug)||$result->slug=="default" ){
                $slug=$result->event_id;
            }

        //get parent cat name
        $parent_cat_id=test_output($result->parent_cat);
        $parent_cat_name=cat_name($parent_cat_id);

        //if there are several cats for one event, display them
        if (isset($result->cat_names)){
            $subcat=test_output($result->cat_names);
        }else{
            $subcat=test_output($result->name);
        }

        //$articleList .= '<div class="well well-sm">' . $result->id . '. <b>' . $result->title . '</b><p>' . test_output($result->description) . '</p></div>';
      include('event-item-agenda.php');
    }

    // We send back the total number of page and the article list
    $dataBack = array('numPage' => $numPage, 'articleList' => $articleList, 'num'=>$numArticles, 'term'=>$term);
    $dataBack = json_encode($dataBack);

    echo $dataBack;

Maybe, you guys, can help me see what I'm doing wrong.

Thanks in advance Sonia

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 keil里为什么main.c定义的函数在it.c调用不了
    • ¥50 切换TabTip键盘的输入法
    • ¥15 可否在不同线程中调用封装数据库操作的类
    • ¥15 微带串馈天线阵列每个阵元宽度计算
    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM