2015-11-02 61 views
2

我正在開發一個搜索器,我做了一個函數,從數據庫獲取數據,將每個廣告保存在一個變量中,並將另一個函數中的分頁保存到另一個變量中,所以他們可以在數組中返回以便在稍後打印在html中。ajax請求php函數沒有收到變量

它的工作方式如下:您點擊購買或租用按鈕,然後進入搜索頁面(/ search?do?= buy/rent),則必須選擇房產類型,可選城市/搜索。 Ajax通過發佈(到search.php,同一文件)發送數據,隱藏第一個容器,並在頁面末尾顯示第二個容器,其中包含具有分頁屬性的列表。

這些是主要的變量,一個腳本來隱藏/顯示容器:

$mode   = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent 
$prop_type  = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX 
$city   = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX 
$zone   = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX 
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT); 

if (isset($page_number) && $page_number >= 1) { 
    $cont1 = 'display: none;'; 
    $cont2 = NULL; 
    // need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET. 
} else { 
    $cont1 = NULL; 
    $cont2 = 'display: none;'; 
} 

這是函數:

function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) { 

    if ($prop_type == 'res') { 
     $table2 = 'res_prop'; 
    } else if ($prop_type == 'com') { 
     $table2 = 'com_prop'; 
    } 

    if ($city != 0) { 
     $optional_cond = ' WHERE t2.city = ' . $city; 
     $optional_cond2 = NULL; 

     if ($zone != 0) { 
      $optional_cond2 = ' AND t2.zone = ' . $zone; 
     } 
    } else $optional_cond = $optional_cond2 = NULL; 

    $mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name'); 

    // pagination 
    if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) { 
     $stmt->execute(); 

     $stmt->bind_result($totalitems); 

     $stmt->fetch(); 

     if (!isset($page)) { 
      $page = (int)$page_number <= 0 ? 1 : (int)$page_number; 
     } 

     $limit = 4; 

     if ($page > ceil($totalitems/$limit)) { 
      $page = ceil($totalitems/$limit); 
     } 

     $start = ($page - 1) * $limit; 

     $stmt->close(); 

     if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.* 
             FROM ' . $table . ' t1 
             INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id 
             ' . $optional_cond . $optional_cond2 . ' 
             LIMIT ?, ?')) { 
      $stmt->bind_param('ii', $start, $limit); 
      $stmt->execute(); 

      $stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4); 
      $test = ""; 
      while ($row = $stmt->fetch()) { 
       if ($status === 0) { 
        $possesion = 'En construcción'; 
       } else if ($status === 1 || $status === 2) { 
        $possesion = 'Inmediata'; 
       } else $possesion = 'Desconocida'; 
       if ($prop_type == 'res') { 
        $is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p> 
          <p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>'; 
       } else $is_res = NULL; 
       $test .= '<div class="box-col"> 
         <div class="col-sm-6 left-side "> 
          <a href="/single?id=' . $id . '"> <img class="img-responsive" src="' . $img1 . '" alt=""></a> 
         </div> 
         <div class="col-sm-6 middle-side"> 
          <h4>Disponibilidad: ' . $possesion . '</h4> 
          ' . $is_res . ' 
          <p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p> 
          <p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p> 
          <p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p> 
          <p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p> 
          <div class="right-side"> 
           <a href="/contact" class="hvr-sweep-to-right more">Contact Builder</a> 
          </div> 
         </div> 
         <div class="clearfix"> </div> 
        </div> 
'; 
       $pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page="); 
      } 
     } //else echo "Statement failed: " . $mysqli->error . "<br>"; 
    } //else echo "Statement failed: " . $mysqli->error . "<br>"; 

    return array($test, $pagination); 
} 

這是主代碼:

if (empty($_GET)) { 
    echo 'under construction'; 
} 
else if (isset($mode) && $mode == 'buy') { 
    $table = 'to_sell'; 
    $targetpage = '/search?do=buy';; 

    if (isset($prop_type)) { 
     $data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage); 
     $test = $data[0]; 
     $pagination = $data[1]; 
    } 
} 
else if (isset($mode) && $mode == 'rent') { 
    $table = 'to_rent'; 
    $targetpage = '/search?do=rent';; 

    if (isset($prop_type)) { 
     $data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage); 
     $test = $data[0]; 
     $pagination = $data[1]; 
    } 
} 
else { 
    echo 'invalid url'; 
} 

這是通過後發送複選框值的AJAX腳本(它不能正常工作,我沒有收到未定義的錯誤$prop_type(我不知道爲什麼???),但我得到它$table2,在於它的if ($prop_type == '')內):

$('.search, .pagination').click(function() { // search button and change page 

    if ($('#res_prop').is(':checked')) { 
     $prop_type = $('#res_prop').val(); 
    } 
    else if ($('#com_prop').is(':checked')) { 
     $prop_type = $('#com_prop').val(); 
    } 

    $.post('search.php', { // same file, maybe self 
     prop_type: $prop_type, 
     city: $('select[name=city]').val(), // optional 
     zone: $('select[name=zone]').val(), // option value="0" by default 
     success: function(){ 
      $('.cont-1').hide(); 
      $('.cont-2').show(); 
     } 
    }); 

}); 

它完美,如果我手動設置$prop_type = 'res';。有任何想法嗎?

的另一個問題是,分頁按鈕鏈接不起作用,它只是觸發AJAX腳本(他們需要發送的數據,以其他方式改變網頁時,腳本將重新啓動)。

我真的很感謝任何腳本的優化。謝謝。

+0

看起來你的語法不在[jQuery網站](http://api.jquery.com/jquery.post/) –

+0

這是否意味着我不能發送'pr op_type'爲'search.php'並沒有重裝再次執行整個PHP腳本?對不起,我從來沒有使用ajax,我完全失去了。 –

+0

不,這並不意味着。我沒有看到你的答案,但從語法上看,成功調用不應該是數據對象的一部分。 –

回答

1

你在這裏混合你的JavaScript和PHP。

在PHP中聲明一個變量$ varname的,在Javascript中,$代表jQuery的運營商。因爲這樣你的代碼說$ ​​prop_type是完全無效的,因爲這是JavaScript代碼。你告訴jQuery執行一些不存在的稱爲prop_type的功能,因此你會得到一個這個未定義的錯誤。

if ($('#res_prop').is(':checked')) { 
    var prop_type = $('#res_prop').val(); 
} 
else if ($('#com_prop').is(':checked')) { 
    var prop_type = $('#com_prop').val(); 
} 

,並變更爲讀取線prop_type: $prop_type,prop_type: prop_type,

+0

謝謝,你是對的。現在我得到'$ test'和'$ pagination'的'undefined variable'。我認爲腳本是錯誤的,成功是在數據內部,我不需要回調,只需執行hide/show()。我在哪裏可以做到這一點? –

0

如果你想使用Ajax導入<div class="results"></div>容器:

你應該使用這個測試,工作代碼:

$(document).ready(function(){ 
    $('.search, .pagination').click(function() { // search button and change page 
     $prop_type = ''; 

     if ($('#res_prop').is(':checked')) { 
      $prop_type = $('#res_prop').val(); 
     } 
     else if ($('#com_prop').is(':checked')) { 
      $prop_type = $('#com_prop').val(); 
     } 

     $.ajax({ 
      method: "POST", 
      url: "go.php", 
      data: { 
       'prop_type': $prop_type, 
       'city': $('select[name="city"]').val(), 
       'zone': $('select[name="zone"]').val() 
      } 
     }).done(function(data) { 
      var _html = $.parseHTML(data); 
      $('.cont-1').hide(); 
      $('.cont-2').show(); 
      $(_html).each(function(i, el) { 
       if (el.className == 'results') { 
        $('.results').html($(el).html()); 
       }; 
      }); 
     }); 

     return false; 
    }); 
}); 
+0

它仍然沒有工作,也許是一個URL問題。我有.htaccess規則重定向到index.php,我使用動態鏈接(在這種情況下「/搜索」,但我已經嘗試過)。任何想法?我得到未定義的索引:'echo $ _POST ['prop_type'];' –

+0

上面的代碼已經過測試,它的工作,所以首先檢查網址並將其更改爲'url:「http://website.com/search 「其次,如果你重定向到主頁,你將看不到更改,所以請停止htaccess的這條規則,最後你可以複製整個錯誤。你也可以在'.done(function(data){console.log(data)})''console.log(data)'中查看返回php搜索文件的內容。 –

+0

好的網址是/ search。我確實警覺(數據);我可以看到整個html代碼,我可以看到'echo'屬性類型:'。 $ _POST ['prop_type'];'它的工作,但只是在警報中,在頁面中,我仍然看到未定義的索引...怎麼了? –