skip to Main Content

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:

<?php
$content = "";
// creates data selector
$content .= "
            <form id = select_data>
                <select id = data_selection>
                    <option value = data1>Data 1</option>
                    <option value = data2>Data 2</option>
                    <option value = data3>Data 3</option>
                    <option value = data4>Data 4</option>
                </select>
            <input id = selected_data type=submit />
            </form>";
// creates table header
$content .= "
            <tr>
                <th>Data</th>
            </tr>";

$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
    $object = // instantiate object by array_id, pseudocode
    $object_data = $object->getData('default-data'); // get default data to display
    // create table item for each object
    $content .= "
                <tr>
                    <td><p>$object_data</p></td>
                </tr>";
}
print $content;
?>

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:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
    $('#select_data').on('submit', function(e){ // get selected data type
        e.preventDefault();
        var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
        $.ajax({
            type: "POST",
            url: 'post.php',
            data: {data_selected: data_selected},
            success: function(data){
                $("p").html(data); // replace all <p> tag content with data
            }
        });
    });
});
</script>

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:

<?php
$attribute = false;
if (isset($_POST['data_selected'])){
    $data = $_POST['data_selected']; // assigns variable out of ajax data
    $object = //instantiate object, again pseudocode
    $object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
    echo $object_data;
}
?>

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:

<td><p id = $array_id>$object_data</p></td>

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

var p_tag_id = <?php echo $array_id; ?>;

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

$("#" + p_tag_id).html(data);

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?

2

Answers


  1. Chosen as BEST ANSWER

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

    <td><p id = $array_id>$object_data</p></td>
    

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

    $("p").each(function() {
        var array_id = $(this).attr("id");
    

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

    $("#" + array_id ).html(data);
    

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

    <script>
    $(document).ready(function(){
        $('#select_data').on('submit', function(e){
            e.preventDefault();
            var data_selected = $("#data_selection :selected").val();
            $("p").each(function() {
                var array_id = $(this).attr("id");
                $.ajax({
                    type: "POST",
                    url: 'post.php',
                    data: {data_selected: data_selected, array_id: array_id},
                    success: function(data){
                        $("#" + array_id).html(data);
                    }
                });
            });
        });
    });
    </script>
    

  2. You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.

    You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):

    var num = data_selected.slice(-1) - 1;
    

    (Subtract 1 because the table rows are zero-indexed)

    Then, in the AJAX code block’s success function:

    $('table tr').each(function(i,v){
        if (i == num){
            $(v).find('td').find('p').html(data);
        }
    });
    

    The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob’s yer uncle.

    I haven’t tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search