Display a list of categories:

<?php foreach($category as $cat) :?> <li><a class="cat" href="#" data-id="<?=$cat['cat_id']?>"><?=$cat['name']?></a></li> <?php endforeach?> 

Jquery:

  $(function(){ var base_url = '<?php base_url();?>'; $('.cat').click(function(){ data={id: $('.cat').data('id')}; console.log(data); $.post(base_url+'getContentByCategory', data, function(){ }); }); 

Which link I wouldn’t click on, sends id = 1 always, although if you look in the browser, then id is different

enter image description here

  • It is strange that generally sends a unit, because you choose a collection of objects with the class cat that does not even have an attribute like data-id - Alexey Shimansky
  • @ Alexey Shimansky, the first one probably has a page :) - Grundy

2 answers 2

Change

data = {id: $('.cat').data('id')};

on

data = {id: $('a', this).data('id')};

You take something else and take it from there. That is the problem.

In your case, you take from all found (or first) attributes data-id , but .cat does not have this attribute. To take this parameter you need to refer to your a tag in the this , where this is the area where .click worked on .cat

  • I understood! Thank you) - Alexander Reizan

It is necessary to change the context of the appeal to this.

 data = { id: $(this).data('id') };