reload only TR if clicked - javascript

I am listing items from SQL in a HTML table <tr>'s and <td>'s. The table is inside a div that is refreshed with jQuery AJAX in every 30 seconds (that is why the div has a unique id). This part works fine. Here is the HTML:
function auto_load()
{
$.ajax({
url: "/folder/content.php",
cache: false,
success: function(data){
$("#live").html(data);
}
});
}
$(document).ready(function(){
auto_load(); //Call auto_load() function when DOM is Ready
});
setInterval(auto_load,30000);
<div id="live">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tr>
<td></td>
<td></td>
</tr>
<!-- and so on -->
</table>
</div>
Now what I want to do is make each of the clickable, but so that if it is clicked,
1) a GET request is sent to a PHP file indicating which particular was clicked;
2) and only that particular (or content inside that ) is refreshed right after that, not the whole page.
I cannot do it with a regular http link, as that way if a is clicked, the whole page would be reloaded.
As this is where my knowledge is short, maybe someone kind can share me some ideas on how to solve this. Thanks!

NOt sure what you want exactly, but if I understand you want to load the row? So you want to listen for a click on the row, read the cells, make an ajax call, and replace the content.
$("#live").on("click", "tbody tr", function() { //listen for click on a table row
var tr = $(this), //the row
tds = tr.find("td"), //the cells of the row
id = tds[0].text(), //the first column text
output = tds[1]; //where to output
$.ajax({
method: "POST",
url: "some.php", //where to post the data
data: { id: id } //value to pass to the server
})
.done(function( result ) {
output.html(result); //output the returned value
})
.fail(function() {
alert( "error" );
});
});
If that is not right, and you want to load the entire table, than you just need to look up the tree to get the div.
$(document).on("click", "tr", function() {
var div = $(this).closest("div");
console.log(div.attr("id"));
div.load("foo.php?id=" + div.attr("id"));
});

$('#myTable').on('click', '.someClass',function () {
var trID=$(this).attr('id');
$(this).find('td').append(new Date());//replace this with your AJAX call
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr id="x" class="someClass"><td>Click Me 1</td></tr>
<tr id="y" class="someClass"><td>Click Me 2</td></tr>
<table>

Related

AJAX Targeting individual anchor elements

I have a PHP-generated table of items. Each row has a link that, when clicked, should expand the row with additional information.
I've tried using JQuery to get the data and return it, which works - but only for the first row. Every link in each row returns data into the first row only. This is because this row has a static ID, which is what I'm targeting.
I thought about trying to assign a dynamic ID when PHP generates each row by dropping a variable in there, but I'd then need to have JQuery return the id of the parent td element whenever the link is clicked so that it targets that specific row, but I don't know how to go about this.
AJAX Function
$(document).ready(function() {
$("a.test").click(function(event) {
$.post("includes/modal.php", { id: event.target.id }, function(response) {
var ticket = document.createElement("p");
ticket.innerText = response;
document.getElementById('myDiv').appendChild(ticket);
});
$(document).ready(function(){
$("button").click(function(){
$('p').hide();
});
});
});
});
PHP Generated rows and columns
echo "
<tr>
<td>$dateChange</td>
<td>$ticketSubject</td>
<td id='myDiv'>
<a class='test' type='button' href='#' id=$ticketID>
View Ticket
</a>
<button>Hide</button>
</td>
<td>$ticketState</td>
</tr>";
I would like the user to click the link on each row and have that row expand with the new data returned by the JQuery.
I can envision this working if the getElementById() part could somehow pull the appropriate column id, which would be dynamically assigned, like so:
<td id=$postID>
I don't know if this would be the best way to go about this, but it's my current thinking. I don't know of any JQuery method that targets each unique instance clicked.
Modify your markup as:
echo "
<tr>
<td>$dateChange</td>
<td>$ticketSubject</td>
<td>
<a class='test' type='button' href='includes/modal.php?id=$ticketID'>
View Ticket
</a>
<button>Hide</button>
</td>
<td>$ticketState</td>
</tr>";
Here, I add href attribute with the link to required page. Also I removed id='myDiv' as id must be unique on the page.
In javascript you just do a POST-request to this href:
$(document).ready(function() {
$("a.test").click(function(event) {
// $(this) gives you the clicked element as jQuery object
$.post($(this).attr('href'), function(response) {
// according to your markup you can do:
$(this).parent().append('<p>' + response + '</p>');
// Instead of these lines below
/*var ticket = document.createElement("p");
ticket.innerText = response;
document.getElementById('myDiv').appendChild(ticket);*/
});
// return false to prevent default action on `a` click
return false;
// I don't know what you expect when put `ready` into `ready`
/*$(document).ready(function(){*/
$("button").click(function(){
$('p').hide();
});
/*});*/
});
});
You need to add unique number in your div id say $ticketID
echo "
<tr>
<td>$dateChange</td>
<td>$ticketSubject</td>
<td id='myDiv$ticketID'>
<a class='test' type='button' href='#' id=$ticketID>
View Ticket
</a>
<button>Hide</button>
</td>
<td>$ticketState</td>
</tr>";
And in your JQuery
$(document).ready(function() {
$("a.test").click(function(event) {
$.post("includes/modal.php", { id: event.target.id }, function(response) {
var ticket = document.createElement("p");
ticket.innerText = response;
document.getElementById('myDiv'+event.target.id).appendChild(ticket);
});
$(document).ready(function(){
$("button").click(function(){
$('p').hide();
});
});
});
});
Hope it helps!

Pass php variable through JavaScript to another php page

I want to pass the id to the next page on clicking the entire row.
I tried to do it myself but I wasn't able to do so .
my code is below :
$( "#tablerow" ).click(function() {
var jobvalue=$("#jobid").val();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="tablerow">
<td><?=$srno?></td>
<td id="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
val() method works for form elements like input, select etc.
Use text() method,
var jobvalue = $("#jobid").text();
Update
An HTML can have only one ID throughout the document. To enable click event for multiple elements and pass the one that is clicked onto another page, change ID attribute to class.
<table>
<tbody>
<tr class="tablerow" >
<td><?=$srno?></td>
<td class="jobid"><?=$row['ID']?></td>
</tr>
</tbody>
</table>
Then you can get the once clicked in JS as follows,
$( ".tablerow" ).click(function() {
/** $(this) will refer to current tablerow clicked
* .find(".jobid") will find element with class `jobid`
* inside currently clicked tablerow
*/
var jobvalue = $(this).find(".jobid").text();
alert(jobvalue);
window.location.href = "jobsview.php?id=" + jobvalue;
});

JSP/Struts2: how to access object bean in selected table row

In my Struts2 application, I have a table that is dynamically populated with data, coming from the database (via Eclipselink JPA). Below that table there's a button that became enabled as soon as a row is selected in the table (jQuery). Now, when that button is clicked, I need to know which row is currently selected, so I can access the corresponding object bean, since I need to pass the bean ID (target_id) into the next page (createexperiment2 action). So, in short, the question is: How can I access the Struts2 object bean that is contained in the selected (clicked) table row?
1. Screenshots:
Before row selection -> After row selection
2. JSP code:
<table id="targets" class="ink-table grey tableSection">
<thead>
<tr>
<th colspan="5" class="align-left">Select your target:</th>
</tr>
</thead>
<tbody>
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr id="row_<s:property value="i"/>">
<td class="all-100"><s:param name="id"><s:property value="target_id"/></s:param></s:url>"><s:property value="name"/></td>
<td class="all-15"><s:param name="id"><s:property value="target_id"/></s:param></s:url>">edit</td>
<td class="all-5">|</td>
<td class="all-15"><s:param name="id"><s:property value="target_id"/></s:param></s:url>">delete</td>
<td class="all-5">?</td>
</tr>
</s:iterator>
</s:if>
</tbody>
</table>
[...]
<a href="createexperiment2" class="ink-button double-vertical-space all-25 buttonSection" id="next" disabled>Next ></a>
3. jQuery code:
$(document).ready(function(){
$('.tableSection tbody tr').click(function()
{
var selected = $(this).hasClass("highlight");
$('.tableSection tbody tr').removeClass("highlight");
$('.buttonSection').attr("disabled", false);
if(!selected)
$(this).addClass("highlight");
});
});
EDIT 1:
With the help of Andrea, I've finally been able to access Struts2 functions with jQuery, the poblem is that I can only access the properties of the last bean on the table (the last one that was accessed when the JSP was rendered, which makes sense). See the updated code below, while I'll try a workaround for this:
JSP:
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr onclick="<s:set var="tid" value="target_id"/>">
[...]
</tr>
</s:iterator>
</s:if>
[...]
<script type="text/javascript">
$(function () {
$('.tableSection tbody tr').click(function(event) {
alert ('<s:property value="%{#tid}" />');
});
});
</script>
EDIT 2:
Now I know which table row index has been clicked, but after hours of trying to assign it to a variable (using Struts tags) and send it to the action, I'm still not getting what I want. I'm not even being able to send this row index to the Action. This is frustrating. Nevertheless, that's how I got to know which row has been selected:
<tr onclick="getRow(this)">
[...]
<script>
function getRow(x)
{
alert("Selected row: "+x.rowIndex);
//return x.rowIndex;
}
</script>
EDIT 3:
This time, I was finally able to send the row ID (a String), to the action. The only remaining issue is that the action gets call twice, the first one on the click event, and the other one because of the href attribute of the a HTML element, which redirects to the desired Struts2 action. Apart of being obviously inneficient, this naturally makes the variable become null on the second call to the action. Do you know how can I somehwow "merge" this 2 calls to the createxperiment2 action into only one? I've tried with the async option in the AJAX call set to false, with no success.
[first, removed the onclick event from the table tr, since I only need to know which row is highlighted when the "Next" button is pressed]. The code currently goes like this:
<script type="text/javascript">
$('#next').click(function(event)
{
var row = $('.highlight').index();
alert (row);
$.ajax({
method: "POST",
url: "createexperiment2.action",
data: { row : row }
});
});
</script>
Q: I have assigned an ID to each table row. How can I know which one is the selected one?
Obtain the object's id with the this keyword:
$('.tableSection tbody tr').click(function(event) {
alert (this.id);
...
Q: how can I use the selected table row ID to access the corresponding bean object (represented in the row itself)?
This is not clear: just submit your id and retrieve the object serverside, no matter if through AJAX or a standard form submit.
Finally, the solution:
First get the ID of the object (I made it with Struts). Then, with the help of an AJAX call, send the ID to the desired action (url: attribute). Upon success of this action, define with the success: callback option where you want to redirect it.
Struts / JSP:
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr id="<s:property value="target_id"/>" class="highlight">
[...]
</tr>
</s:iterator>
</s:if>
jQuery:
<script type="text/javascript">
$('#next').click(function(event)
{
var tid = $('.highlight').attr("id");
$.ajax({
method: "POST",
url: "createexperiment2.action",
data: { tid : tid },
success:
function()
{
//alert("TID -> "+tid);
window.location = "loadworkloads.action";
}
});
});
</script>

Detecting new tr or content change

I have a bunch of tr, that represent a cart
<tr class="cart_row">
<td>Product</td>
<td>£20</td>
<td>2</td>
</tr>
<tr class="cart_row">
<td>Product 2</td>
<td>£50</td>
<td>1</td>
</tr>
This gets updated via ajax when an item has been added.
What I'm looking to do, is to detect when the cart has been updated, i.e a new <tr> with a class of cart_rowor if the contents of an existing <tr> has been updated
Can I do this with jQuery?
Thanks
I would suggest this:
// a function to make a string out of thew data
function getData() {
var data = $('tr.cart_row td').map(function (el) {
return this.innerHTML;
}).get().toString();
return data;
}
//before the Ajax:
var valuesBefore = getData();
// do Ajax
//after the Ajax, ideally inside the callback (remeber ajax is async)
if (valuesBefore != getData()){ //do something };
Example
You can, with this:
$("#yourTable").on("DOMSubtreeModified", function() {
alert("table changed! row added");
});
See the browser support here: http://www.quirksmode.org/dom/events/#t18
EDIT However, it's getting deprecated
Hope this helps. Cheers
As far as I know, there is no event for this action. You should implement this with the help of setTimeout function. Set a function which checks if the count of needed elements changes.

Can't click button more than one time when append html data

I've a problem with jquery. I use ajax to send id to delete from DB and then return html file to update content without reload page (I use struts 2) , first time run or reload page my button work fine ( row was deleted and my content was updated) but when I try to click button again , it doesn't respond.
My script
$(document).ready(function() {
$(".btnEdit").click(function() {
alert("Edit");
});
$(".btnDelete").click(function() {
id = $(this).attr('id');
alert("Delete ID : " + id);
$.ajax({
url: "delete",
type: 'POST',
data: {'id': id},
cache: false,
success: function(data, textStatus, jqXHR) {
$('.catagoryContent').remove();
$('.container').append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
});
});
Sorry, I forgot return data code.
<div class="catagoryContent">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tbody>
<s:iterator value="catagoryList" var="catagory">
<tr>
<td>${catagory.id}</td>
<td>${catagory.name}</td>
<td>
<button class="btn btn-primary btnEdit" id="${catagory.id}">Edit</button>
<button class="btn btn-warning btnDelete" id="${catagory.id}">Delete</button>
</td>
</tr>
</s:iterator>
</tbody>
</table>
At document ready you initialize all tags with class "btnDelete" to the click function.
When you do a successfully ajax call, you replace all your content with response from the server.
At that point you remove all your buttons and add new data with new buttons.
jQuery is not listening to these buttons because the $(".btnDelete").click(... was only set at page load.
if you change
$(".btnDelete").click(function() {
to
$(document).on("click", ".btnDelete", function() {
it will still work after you add new data to .container
The "on" function also triggers when you dynamically add new tags with class ".btnDelete" (See here)
You aren't listening to the click event on your updated html.
You should use
$list.on('click', '.btnEdit', function() { ... })
where $list is the element containing the items (probably a <ul>)
This is because click event handler is attached at the page startup.
But when you reload the part of your page, old button with onclick handler is being removed.
The decision is to use
$(document.body).delegate('.btnDelete', 'click', function(){...})
instead of
$(".btnDelete").click(function(){...})
This way you will attach event handler to body element (which will fire always), and jQuery will check whether the clicked element has class .btnDelete, or not.
So it will work even if you delete these buttons and then insert new ones.
Another approach is to attach onclick handlers to the buttons every time they created, but I think the first approach is easier

Categories

Resources