Skip to content
Advertisement

Buttons with dynamic ajax text

In my php page I have a row of buttons which each have some values (5 in this example). These values shall be send into a ajax script which do some calculation to values and return the result for each button without reloading the homepage. In this example the result will be

FRANK=5 (button 1)

FRANK=frank (button 2)

FRANK=48 (button 3)

FRANK=Bo (button 4)

FRANK=test (button 5)

When I press the first button I should see result 1 on the button. When I press the next button I should see result 2 on the button.

I only have one result returned on button 1 since all buttons has the same container for the return value. I need more containers for return values and I could add $i to the container: . This will give me different containers to return the result to. But how can I use $i in the javascript. My problem is also that var x in the javascript always will be the value from the first button. Again I could add $i to the id=”x”: id=”x’.$i.'” but still I only have document.getElementById(“x”).value to read the x value in the javascript.

I hope that somebody help me to finish the code here.

Mainpage:

JavaScript

hide-ajax-scripts.php contains:

JavaScript

hide-ajax-svar.php contains the calculation. Here will come a lot more calculations and storing of values in database.

JavaScript

Advertisement

Answer

You can pass this inside your function call where this refer to current button which is clicked .Also , you cannot use same ids for mutliple elements instead use class selector . So, change your php code like below:

JavaScript

Then , add this as parameter inside your function and then use el.value to get the button value which is clicked and el.querySelector(".container").innerHTML to add result inside the span tag where button has been clicked. So, change your js code like below :

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement