mohamed maher
mohamed maher

Reputation: 37

Can't excute a function when i click on li element

I have an HTML list like this:

<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>

when I click on "2014" for example, I need to hide other list and show only the clicked one then pass this year to php file, catch this year and connect to a database baking with other data related to this year then list this new data at the end of list, and I tried this:

jQuery part:

<script> 
$('.year').click(function(){
var path=$(this).text();
$(".year").toggle(200);
$(this).toggle(200);
$.post("test.php",{p:path},function(data){
$(".years").append(data);
});

// last part of script
$(".col_1").click(function(){
//whatever 
});

</script>

test.php:

if(isset($_POST['p']){
$year=$_POST['p'];
$db_connection=new mysqli(localhost,USER,PASS) ;
$query="select*from user.info where year=$year" ;
$db_connection->query($query);
$rows=$db_connection->num_rows;
for($i=0;$i<$rows;$i++){`
$result->data_seek($rowP);
$result->fetch_assoc()["col_1"];
$returned_data.="<li class='col_1'>$result</li>";
}
echo "$returned_data";
}

All of this work well and the data show up in the web page but the last part of script doesn't work and nothing happen when i click on any element of this list. Is the reason because the <li class='col_1'> coded by php or what?.. Thanks for help.

Upvotes: 1

Views: 104

Answers (1)

Curiousdev
Curiousdev

Reputation: 5788

just move $(".col_1").click(function(){ inside Success function in ajax

$('.year').click(function(){
  debugger;
  var path=$(this).text();
  $(".year").toggle(200);
  $(this).toggle(200);
  $.post("test.php",{p:path},function(data){
    $(".years").append(data);
    $(".col_1").click(function(){
    //alert();
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>

Upvotes: 1

Related Questions