Facebook  Twitter  Google +  Linkedin


Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/lwegabab/public_html/old/plugins/content/al_facebook_comments/al_facebook_comments.php on line 516

Warning: file_get_contents(https://api.facebook.com/restserver.php?method=links.getStats&urls=https://www.old.yourictmagazine.com/howtos/935-codeigniter4-howto-fetch-data-by-id-button-click-from-database-using-jquery-ajax): Failed to open stream: no suitable wrapper could be found in /home/lwegabab/public_html/old/plugins/content/al_facebook_comments/al_facebook_comments.php on line 516

Warning: Undefined array key 1 in /home/lwegabab/public_html/old/plugins/content/al_facebook_comments/al_facebook_comments.php on line 521

Codeigniter4 Howto fetch data by ID with button click from database using JQuery Ajax

Learning has never stopped. That is why I wanted to share this little piece of code if it could be helpful to another codeigniter lover or developer.

Let's say you want to display products from their particular categories.

So it will start with a point where you have created buttons that show names of categories and every time a user clicks on a particular category button, products will display from it.

 Categories

Model

//show all categories
public function getAll()
{
  $builder = $this->db->table('product_category');
  $results = $builder->get()->getResult();
  return $results;
}

Controller

  
public function index()
{
  //show category and products
  $data['productCategory'] = $productCategoryModel->getAll();
  return view('products/all', $this->data);
}

Views

NOTE: This view file all.php is the same to display also products but in a separate div with id=”products”. Failed to get code for view file here. so i have provided a screenshot

 view file code

PRODUCTS

Model

//Get products in a particular category
    public function getCatProducts($id)
    {
        $builder = $this->db->table('product');
        $builder->where('category_id', $id);
        $builder->join('product_category', 'product.category_id=product_category.cat_id');
        $results = $builder->get()->getResult();
        return $results;

    }

Controller

public function action()
	{
        if($this->request->getVar('action'))
		{
			$action = $this->request->getVar('action');
            if($action == 'get_products')
			{
                $productModel = new ProductModel();
				$myproducts = $productModel->getCatProducts($this->request->getVar('cat_id'));

				echo json_encode($myproducts);                
			}
        }
    }

NOTE: “all.php” code is already up. Just ensure you have the same controller file to handle categories and products queries.
The last piece of code needed is this for JQUERY AJAX

JQUERY AJAX (in all.php) view file.




    function showproducts(cat_id)
    {
        //console.log(cat_id);
        $.ajax({
                method:"GET",
                url:""+cat_id,
                dataType:"json",
                processData: false,
                contentType: false,
                cache: false,
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                success:function(data)
				{
                    //console.log(data);
                    //alert(data);
                    var html = '
Products
';
					
                    for(var count = 0; count < data.length; count++)
                    {
                        html += '

'+data[count].product_name+'

';
                    }
			
                    $('#products').html(html);
                },
				error: function(xhr, status, error){
				var errorMessage = xhr.status + ': ' + xhr.statusText
				alert('Error - ' + error);
				}
            });
    }

 

 

That should be able to help display your product with button click into another defined Div.

NOTE:
Ensure jquery is loaded

Enjoy codeigniter