1

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?

2
  • 3
    Creating dynamic elements with duplicate ID's can cause multiple problems but I don't see where you attempt to append this button. You haven't even stored it into a variable so as your source code stands it will throw a syntax error. I suggest you format the source code in your question so it doesn't mislead anyone into thinking you are trying to execute the script as it looks in your question. Commented Dec 27, 2017 at 6:13
  • 1. convert id="btn" to class="btn", because id need to be unique per element.2.What data you are fetching on button click(add that code so that we can check). 3. Add the HTML part also for more clarity Commented Dec 27, 2017 at 6:18

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

There are two ways of doing this, I would prefer this one:-

  1. Add the onclick event to button and pass unique id or name to it.

    <button onclick="fun('<?=$name?>')">click me</button>
    
  2. In method fun call the ajax request and pass the name or id to it which you recieved as a function parameter.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.