Skip to content
Advertisement

PHP AJAX HTML: changing unique table data in foreach loop

I’m new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.

I have a PHTML template which looks like the following:

JavaScript

This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag. And then I have some Javascript which looks like the following:

JavaScript

This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:

JavaScript

The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.

I tried to identify each <p> tag with the following:

JavaScript

And then creating a new Javascript variable out of the array ID:

JavaScript

And finally making the Ajax success function target element ID’s based on var p_tag_id:

JavaScript

While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.

How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?

Advertisement

Answer

I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:

JavaScript

Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:

JavaScript

And finally I made the Ajax success target elements based on their ID:

JavaScript

Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!

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