[英]how to pass variable from jquery ajax to php mvc
我正在使用php-mvc並使用ajax添加搜索功能。 如何將值從input
傳遞到模型並查詢值。 我試圖在getAllUsersProfiles
方法內添加$_GET['searchData']
,但未獲取該值。
HTML:
<input type="text" id="searchData" placeholder="search name here..." />
...
<!--where I want to output the search result -->
<tbody id="account_results"></tbody>
JS:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val());
if(searchValue !== ''){
$.get("<?php echo URL; ?>admin/index/", function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
PHP模型:
public function getAllUsersProfiles()
{
$sql = "SELECT id, username, email, active, firstname, lastname
FROM users";
if(isset($_GET['searchData'])) {
$sql .= " WHERE CONCAT(TRIM(firstname), ' ', TRIM(lastname))
LIKE '%:searchData%'";
$sth = $this->db->prepare($sql);
}
else
//if search input is not set, output all of the list.
$sth = $this->db->prepare($sql);
$sth->execute();
$all_users_profiles = array();
foreach ($sth->fetchAll() as $user) {
//code here..
}
return $users;
}
PHP控制器:
class Admin extends Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$admin_model = $this->loadModel('Admin');
$this->view->users = $admin_model->getAllUsersProfiles();
$this->view->render('admin/index');
}
您的PHP代碼沒有獲得searchData值,因為您沒有將其與GET請求一起發送。 在您的JS部分中嘗試以下操作:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val()), url = '<?php echo URL; ?>/admin/index/?searchData=' + searchValue;
if(searchValue !== ''){
$.get(url, function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
然后可以在PHP中使用$_GET['searchData']
獲取值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.