user982124
user982124

Reputation: 4622

Passing Unique ID to AJAX Script

I'm working on my first AJAX script with some PHP pages - it's my first time with AJAX and I've finally got the script to work. I'm also a bit of a Javascript newbie too.

I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. We've now changed the "Select" link to load via AJAX so the search results page doesn't refresh.

To finish the AJAX changes I now need to pass a unique ID for each of the table cells that has the AJAX link to the script. I'm using PHP to generate a unique ID for each table cell by using the $bookID variable as follows:

<td class="hidden-narrow" id="<?php echo 'selectRecord'.$bookID; ?>">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo '<a href="select" onclick="return selectRecord('.$bookID.')" class="center">Select</a>';
}
?>
</td>

I now need to update my script to work with the unique ID's - to get it working I hardcoded it to an ID named "selectRecord" using an example script that I found. Here's my script:

function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
  // IE6, IE5
  var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
  if ((this.readyState == 4) && (this.status == 200)) {
     document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false;  // Do not follow hyperlink

I gather I need to change this line:

document.getElementById("selectRecord").innerHTML="Selected";

but not sure of the syntax to handle unique ID's for each table row cell.

Upvotes: 1

Views: 545

Answers (2)

Kim G.
Kim G.

Reputation: 196

You can pass the id to the getElementById function:

document.getElementById("selectRecord" + id).innerHTML="Selected";

Upvotes: 1

user2625787
user2625787

Reputation:

Have you tried

document.getElementById(id).innerHTML="Selected";

? id should get enclosed by the readystate function and keep its value.

Upvotes: 0

Related Questions