rod122
rod122

Reputation: 105

Ajax posting from dynamically created table

newbie to ajax here. I am trying to post some data to a php file on my server, however, the data is not passing thru. I have a dynamically created table from the results of a query. I am trying to use document.getElementById but that does not grab my data (and it makes sence that it doesn't since each dynamically created row will have the same id I guess) I have also tried passing the the variables in a function like so:

print("<tr onclick='ajax_post({$result["date"]}, {$result["work"]});'>");

and on the js function grabbing the variables like so:

ajax_post(a, b){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create variables to send to our PHP file
var url = "ajaxform.php";
var dt = a;
var wk = b;
var vars = "date="+dt+"&workout="+wk;
}

but this doesn't work here. Here is my code:

<script>
function ajax_post(){
    // Create our XMLHttpRequest object
 var hr = new XMLHttpRequest();
// Create variables to send to our PHP file
var url = "ajaxform.php";
var dt = document.getElementById("date").value;
var wk = document.getElementById("work").value;
var vars = "date="+dt+"&workout="+wk;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables       in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status     div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>

<p id="status"></p>

<div>
  <table class="table table-striped">  
    <thead>
      <tr>
        <th class="bold">Date</th>
        <th class="bold">Work</th>
        <th class="bold">Mood</th>              
      </tr>
    </thead>
    <tbody>      
<?php       

        foreach ($results as $result)
        {   
            print("<tr onclick='ajax_post();'>");

                print("<td class='date' id='date' name='date'  value='{$result["date"]}'>{$result["date"]}</td>");
                print("<td id='workout' name='workout' value='{$result["work"]}'>{$result["work"]}</td>");
                print("<td>{$result["mood"]}</td>");        

            print("</tr>");                

        }                     

  ?>        

  </tbody>   
 </table>    

</div>

Any help would be greatly appreciated. Im open to a jquery solution if it is not feasable to do this with plain js.

Thanks!!!!!!

Upvotes: 0

Views: 1369

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

I would use $.ajax() to simplify things a bit. But besides that, you should use classes not ids to target your elements because ids should always be unique (only one element should have that id) while any number of elements can have the same class.

When a user clicks a row, find the elements you need in that row and get their values, then send them in the ajax call.

Here's an example:

jsFiddle

$('tr').click(function() {
  var row = $(this);
  var url = "ajaxform.php";
  var dt = row.find(".date").text();
  var wk = row.find(".work").text();
  var vars = "date=" + dt + "&workout=" + wk;
  $.ajax({
    type: "POST",
    url: url,
    data: vars,
    success: function(response) {
      // handel successs
    },
    error: function(response) {
      // handel error
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table>
    <tr>
        <td class="date">1/2/2015</td>
        <td class="work">legs</td>
    </tr>
    <tr>
        <td class="date">1/3/2015</td>
        <td class="work">arms</td>
    </tr>
    <tr>
        <td class="date">1/4/2015</td>
        <td class="work">lats</td>
    </tr>
    <tr>
        <td class="date">1/5/2015</td>
        <td class="work">calves</td>
    </tr>
    <tr>
        <td class="date">1/6/2015</td>
        <td class="work">quads</td>
    </tr>
</table>

Upvotes: 1

Related Questions