I have a menu which get its items from database.
I want to get the menu id of clicked menu in following for each:
public function gen_menu($menuItems, $pId = 0)
{
$menu = '';
$ulStart = 0;
$base_url = base_url();
$uri = $this->uri->segment(1);
foreach($menuItems as $row)
{
if($row->parent_id==$pId)
{
if($ulStart==0) { $menu .= "<UL>"; $ulStart++; }
$url = $row->item_url;
stripos($url,$base_url)===0 || $url==""?$base_url = base_url():$base_url="";
{
if($row->external==1){
$menu .= '<LI><a href="'.$row->custom_url.'" title="'.$row->alt_title.'">'.$row->item_title.'</a>'.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
else{
$class = ($uri==$row->custom_url)?"class='selected'":"";
$menu .= '<LI '.$class.'><a href="'.site_url($row->custom_url).'/'.$row->item_id.'" title="'.$row->alt_title.'" onclick="'.$this->get_id($row->item_id).'">'.$row->item_title.'</a>'.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
}
}
}
if($ulStart!=0) { $menu .= "</UL>"; }
return $menu;
}`
When I am using onclick in it returns the last id of table always.
Try this:
You had
$row->item_idinside the quoted string, so it wasn’t expanded. You should have gotten a javascript error from that.UPDATE:
The problem you’re having is that you’re confusing server-side and client-side actions. The code in this PHP script all runs on the server when it’s creating the page to send to the user. If you’re setting a session variable in the loop, the variable will contain the value from the last iteration. Putting PHP code inside
onclickdoesn’t run it when the user clicks, it runs it when the server is composing theonclickattribute to put in the HTML that gets sent to the browser.If you want to do something on the server when the user clicks, you need to put a Javascript function in the
onclickattribute, and that function should use AJAX to call another PHP script.