Opencart Ajax – Using Ajax we can call our controller function and load data without refreshing page.For this we have to create a function in our controller file like and you can call it using ajax.
//in your controller file your ajax function
public function Ajaxcall(){
$this->load->model('module/wkajax_demo');
$this->language->load('module/wkajax_demo');
$json = array();
if(isset($this->request->post['call']) AND isset($this->request->post['data'])){
$data = $this->request->post['data'];
$call= $this->request->post['call'];
$result = $this->model_module_wkajax_demo->yourModelFunction($data,$call);
$json['success'] = $text_main;
}
$this->response->setOutput(json_encode($json));
}
//in your .tpl file after any event use ajax to call controller function
$.ajax({
type: 'post',
url: 'index.php?route=module/wkajax_demo/Ajaxcall',
//add data like this using &
data: 'call='+Ajax+'&data='+YourData,
dataType: 'json',
success: function(json) {
if(json['success']) {
//you can use data according to need
console.log(json['success']);
}else{
alert('error');
}
}
});
4 comments
Simply you can send your filters values to your controller and then can perform queries on that like create object for product filters like
var product_filters = {
‘price’ : $(‘#price’).val(),
‘name’ : $(‘#name’).val(),
//etc
};
then pass this variable to your ajax call
data: product_filters,
and in controller you can get it’s key like explained in blog, now just do your logic based on passed values and return filtered Product result.
It’s difficult to provide full example of filtering using product attributes. But let me tell you that the product attributes and filters are two different entities. Although, both of them can be used to filter products, still filters are preferred to filter products over the attributes.
Here’s a little example on size that can make you understand easily if you’re aware of ajax and jquery.
View file code:
Size
Small
Medium
Large
Extra Large
$(‘input[name=’size”).change(function () {
$.ajax({
url: ‘index.php?route=product/product/filter’,
dataType: ‘json’,
type: ‘post’,
data: {size: $(this).val()},
success: function(json) {
// json contains the filtered products which can be used to update products
}
});
})
Controller Code (can be written in product.php):
public function filter () {
$this->load->model(‘folderName/modelName’);
$size = $this->request->post[‘size’];
$products = $this->model_folderName_modelName->functionName($size); // In this function, query for fetching products is written for fetched according to their size
$this->response->addHeader(‘Content-Type: application/json’);
$this->response->setOutput(json_encode($products));
}
Hope this will give you an idea to write code in opencart. Best of Luck