Reputation: 188
I created a dynamic button,and used ajax to call it when clicked. when each of the button is clicked it fetches a list of items from a website, which makes it dynamic.
foreach($items as $item_link){
$i++;
$item_name = $name[$i];
<button type="button" id="btn" name="btn" value="'.$item_link[$i].'" onclick= " getItem(this.value);">'.$item_name.'</button>
}
I noticed that when each of the buttons are clicked it only return the same value,instead of dynamically returning different values of the button. My question is: what could be the cause? Although the button is not in a form, could that also be a reason?
Upvotes: 1
Views: 53
Reputation: 264
One problem is that you are using the same ID for all the buttons and that will bring unexpected behavior to the browser. You need to change for something like this:
foreach($items as $item_link){
$i++;
$item_name = $name[$i];
<button type="button" id="'.$item_link[$i].'" name="btn" value="'.$item_link[$i].'" onclick= " getItem(this.value);">'.$item_name.'</button>
}
Or simply get rid of the ID and use a class instead
Upvotes: 1
Reputation: 72269
1.Initially and in foreach()
also change button id
to class
.
2.You haven't echod
your button, so i don't think it's coming at all. So echo
it and sorrund the button with quotes.
Proper code:-
foreach($items as $item_link){
$i++;
$item_name = $name[$i];
echo '<button type="button" class="btn" name="btn" value="'.$item_link[$i].'" onclick= "getItem(this.value);">'.$item_name.'</button>';
}
Note:-
id need to be unique per element, otherwise when you are using it in jquery you will get always first element data.
Upvotes: 1
Reputation: 2091
There are two ways of doing this, I would prefer this one:-
Add the onclick event to button and pass unique id or name to it.
<button onclick="fun('<?=$name?>')">click me</button>
In method fun call the ajax request and pass the name or id to it which you recieved as a function parameter.
Upvotes: 1