#javascript #php #ajax #codeigniter
#javascript #php #ajax #codeigniter
Вопрос:
Я пытаюсь показать динамический результат поиска на странице поиска, где я использую jquery ajax для получения данных из библиотеки разбивки на страницы codeigniter, но все работает нормально, даже когда я проверяю ответ ajax в инструментах разработчика, я вижу результат, но не могу показать на странице. Ниже приведен код, который я использовал:
search_page.php — (просмотр файла)
<?php include("includes/header.php");?>
<!-- Search Result Will Be Show Here -->
<div class="row" id="search_result_section"></div>
<!-- Search Result Pagination Will Be Show Here -->
<div id="search_result_section_pagination_link"></div>
<?php include("includes/footer.php");?>
jQuery Ajax (помещается в нижний колонтитул — footer.php — просмотр файла)
$(document).ready(function(){
<?php if($this->uri->segment(1) === 'search'): ?>
// Search Query
load_search_page_data(1);
function load_search_page_data(page)
{
var q = $('#search').val();
if(q == '')
{
q = '';
}
$.ajax({
url:"<?php echo base_url('search/result/'); ?>" page,
method:"POST",
dataType:"JSON",
data:{q:q},
success:function(data)
{
console.log(data);
$('#search_result_section').html(data.search_result_section);
$('#search_result_section_pagination_link').html(data.search_result_section_pagination_link);
}
});
}
$(document).on('click', '.pagination li a', function(event){
event.preventDefault();
var page = $(this).data('ci-pagination-page');
load_search_page_data(1);
});
// Search Query
<?php endif; ?>
});
Search.php (файл контроллера)
class Search extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Crud', 'crud');
$this->load->helper('url');
$this->load->library('pagination');
}
public function index($page = null)
{
$data['page'] = 'search';
$data['seo_title_data'] = 'Search Result | '.$this->crud->getSetting('default_seo_title');;
$data['seo_description_data'] = $this->crud->getSetting('default_seo_description');
$data['seo_keywords_data'] = $this->crud->getSetting('default_seo_keywords');
$data['seo_canonical_data'] = base_url('search.html');
$data['q'] = $this->input->post('q');
$this->load->view('theme/search_page', $data);
}
public function getSearchData()
{
sleep(1);
$q = filter_var($this->input->post('q'), FILTER_SANITIZE_STRING);
$config = array();
$config['base_url'] = '#';
$config['total_rows'] = $this->crud->get_search_count($q);
$config['per_page'] = 3;
$config['uri_segment'] = 3;
$config['use_page_numbers'] = TRUE;
$config['full_tag_open'] = '<div class="product-pagination"><ul class="pagination">';
$config['full_tag_close'] = '</ul></div>';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['next_link'] = '<i class="fa fa-angle-double-right"></i>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = '<i class="fa fa-angle-double-left"></i>';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='active'><a href='#'>";
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['num_links'] = 2;
$this->pagination->initialize($config);
$page = $this->uri->segment(3);
$start = ($page - 1) * $config['per_page'];
$output = array(
'search_result_section_pagination_link' => $this->pagination->create_links(),
'search_result_section' => $this->crud->search($q, $config["per_page"], $start)
);
// echo '<pre>';
// print_r($output);
echo json_encode($output);
}
}
Crud.php (файл модели)
// Get Product Count
public function get_search_count($q)
{
$qarray = explode(' ', $q);
$this->db->distinct();
$this->db->select('*');
$this->db->from('products');
$this->db->like('product_name', $q, 'both');
if (count($qarray) > 1) {
foreach ($qarray as $s) {
$this->db->or_like('product_seo_title', $s, 'both');
$this->db->or_like('product_seo_description', $s, 'both');
$this->db->or_like('product_seo_keyword', $s, 'both');
}
} else {
$this->db->or_like('product_seo_title', $q, 'both');
$this->db->or_like('product_seo_description', $q, 'both');
$this->db->or_like('product_seo_keyword', $q, 'both');
}
$query = $this->db->get();
echo $query->num_rows();
}
// Get searched product data
public function search($q, $limit = null, $start = null)
{
$output = '';
$qarray = explode(' ', $q);
$this->db->distinct();
$this->db->select('*');
$this->db->from('products');
$this->db->like('product_name', $q, 'both');
if (count($qarray) > 1) {
foreach ($qarray as $s) {
$this->db->or_like('product_seo_title', $s, 'both');
$this->db->or_like('product_seo_description', $s, 'both');
$this->db->or_like('product_seo_keyword', $s, 'both');
}
} else {
$this->db->or_like('product_seo_title', $q, 'both');
$this->db->or_like('product_seo_description', $q, 'both');
$this->db->or_like('product_seo_keyword', $q, 'both');
}
if($limit != null amp;amp; $start != null)
{
$this->db->limit($limit, $start);
}
$query = $this->db->get();
// return $query->result();
foreach ($query->result() as $product) {
$output .= '<!--Single Product Strat-->
<div class="col-lg-4 col-xl-3 col-md-4 product__box__container my-3">
<div class="single-product mb-40">
<div class="single-product">
<div class="product-img">
<a href="'.$product->product_vanity_url.'.html">
<img src="'.$product->product_img_one.'" alt="'.$product->product_name.'">
</a>
<div class="product-action">
<ul>
<li>
<a href="'.base_url($product->product_vanity_url).'.html" data-toggle="tooltip" title="Add To Cart" class="add_cart" data-productid="'.$product->product_uid.'">
<i class="fa fa-shopping-cart"></i>
</a>
</li>
</ul>
</div>
</div>
<div class="product-content">
<h4><a href="'.base_url($product->product_vanity_url).'.html">'.$product->product_name.'</a></h4>
</div>
<div class="product-price">
<span class="price">₹ '.number_format($product->product_price, 2).'</span>
<span class="regular-price">₹ '.number_format($product->product_price_mrp, 2).'</span>
</div>
</div>
</div>
</div>
<!--Single Product End-->'.PHP_EOL;
}
return $output;
}
routes.php (файл маршрутов)
$route['search'] = 'Search';
$route['search/result/(:any)'] = 'Search/getSearchData/$1';
Комментарии:
1. Можете ли вы показать вывод
data
?2. вы можете найти здесь ….. infipick.com/shop/search.html
3. Привет, я проверяю это, запрос ajax выполняется при загрузке страницы, но не нашел ни
console.log(data);
одного, потому что я думаю, что при загрузке ваше окно поиска не имеет никакого значения. Кроме того, вы отправляете свою форму, поскольку я вижу, что ваше окно поиска находится под тегом формы?