Selecting a unique cell from a dynamic generated table - php

Here goes my problem: this is the table
I want to click on delete column of a particular row say row no2 then I should select the value OFFICED-Id of that particular row row no.2
The problem is that table is being generated dynamically by the following code
<tbody>
<?php for($i=0;$i<count($detail1);$i++):?>
<tr>
<td><?=$detail1[$i]['id'];?></td>
<td><?=$detail1[$i]['officer_id'];?></td>
<td><button onclick='alert("<?=$detail1[$i]['password']?>")' > change</button></td>
<td><i class=" del glyphicon glyphicon-minus"></i></td>
</tr>
<?php endfor; ?>
</tbody>
I am trying to select that particular cell of a row by applying this jQuery function but I am getting error in the console and it's not working too
the variable id is going to save that particular cell value
$(document).ready(function(){
$(".del").click(function(){
var answer = confirm ("Are you sure you want to delete from the database?");
var id= <?php echo $detail1[$i]['id'];?>;
if (answer)
{
// your ajax code
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>Admin/del', //We are going to make the request to the method "list_dropdown" in the match controller
data: {'id':id}, //POST parameter to be sent with the tournament id
//With the ".html()" method we include the html code returned by AJAX into the matches list
success: function(resp) {
alert('you have successfully deleted');
},
error: function(resp) {
console.log('error');
console.log(arguments);
}
});
}
});
});
The error in the console is
SyntaxError: expected expression, got '<'
What I figured out that this line var id= <?php echo $detail1[$i]['id'];?> is causing error and making my jQuery call not functioning
Is there alternative to select that particular cell OFFICED OF A ROW from a dynamic table by any event?

var id= <?php echo $detail1[$i]['id'];?>
Looks like $i is not defined, so id should be null. And so the issue.
Select id something like this. Please test, might need extra work:
var id= $(this).closest('tr').find('td.id').html();
And HTML <td> of id line should look something like:
<td class="id"><?=$detail1[$i]['id'];?></td>

Related

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:
<?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?
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.
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>

jquery - ajax - problem with update columns one by ones

i want to update each columns acording by id, when i click on an image, without refresh all the page. my codes just update last ids column when i click each on images.
index.php:
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid=1");
while($rw=mysqli_fetch_assoc($rzp)){$id=$rw['id'];
echo $id;?><img id="up" src="pc3/up.png" alt=""><br>
<?php }?>
<script>
$(document).ready(function() {
var id = <?php echo $id;?>;
$(document).on("click","#up",function() {
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id},
async :false
}).done(function(msg2) {
alert(msg2);
});
});
});
</script>
y2.php:
$id=$_POST['id'];
mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
thanks
There are a couple things immediately wrong here:
You are re-using id values in your HTML, which is invalid.
Your var id = ... JavaScript code always has the last value from your data, and you're explicitly using that every time instead of any value from your HTML element.
Let's simplify. First, echo your HTML elements to include (1) a class to use for triggering the click handler and (2) the ID that the click handler needs:
<?php
while($rw=mysqli_fetch_assoc($rzp)){
$id=$rw['id'];
echo $id;
?>
<img class="up" src="pc3/up.png" alt="" data-id="<?php echo $id; ?>"><br>
<?php } ?>
(Note: There's probably a much cleaner way to do that. I'm attempting to maintain the coding style you currently have, but you should definitely look into cleaner approaches of writing code overall.)
Now you have a bunch of images with (1) a class called "up" and (2) a data- attribute with the ID you need upon clicking. Your click handler can now use that information:
$(document).on("click", ".up", function() { // use the class as the selector
var id = $(this).data('id'); // get the data-id value from this specific element
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id}
}).done(function(msg2) {
alert(msg2);
});
});
(Note: I also removed async: false because one should never use async: false. If there's some reason you think you need to use it, that's a different problem entirely and one that should be addressed as well.)

Getting ID value of clicked row - jquery

ok .. quick overview.
I have a table and each row has the ID attribute value assigned based on the ID form the db record
I have a click event that shows / hides a div and I want the data it displays
in that div to be based on the results from the DB for that corresponding ID value
Here is my table code showing the ID
<td class="hidden-xs">
<a data-toggle="toggle" href="#comp_info" class="showcompinfo" id="<?php echo $complistr['company_id'];?>">
<?php echo $complistr['registered_office_address'];?>
</a>
</td>
This is where I want the data displayed
<div class="panel-heading">
<i class="fa fa-building" style="color:orangered"></i>
<span id="showcompname"></span>
</div>
Here is the jquery code
$(document).ready(function () {
$('#comp_info').hide();
$('.showcompinfo').click(function () {
var id = $('.showcompinfo').attr('id');
$('#comp_info').toggle();
var companyid = id;
var dataString = 'companyid=' + companyid;
$.ajax({
type: 'POST',
url: '../inc/dataforms/complist.php',
data: dataString,
success: function (result) {
$('#showcompname').html(result);
}
});
});
});
Here is the PHP code for the query
include('../config.php');
if (!empty($_POST['companyid'])) {
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc, "SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if ($result) {
echo $result['name'];
}
}
Please dont say .. your code is open to SQL injection .. i've said before its on a closed system with no external access and the people using it can barly use a PC
All I want it to do is to display the company name in the showcompname span box
If possible am I also able to display different result data in different divs ?
To retrieve the ID from the clicked <a> tag, in your jQuery code change this line:
var id = $('.showcompinfo').attr('id');
For this one:
var id = $(this).attr('id');
That way you are retrieving the id attribute from the element that was the target of the click event.
Your original code was retrieving an array of ids of all elements with the class showcompinfo.
Your problem lies in the selector for the id, var id = $('.showcompinfo').attr('id');.
You are selecting every showcompinfo in the page.
You would be better off by using this in that selector.
This would correctly select your id, based off the clicked td.
var id = $(this).attr('id');

Delete button works on only first row not on the rest of the rows

I have fetched the values(card details) from an array and put them in an html table, I have also added the delete button for deleting the particular card.
I am deleting this through ajax. When i click on the delete button of the first row, it works perfect but when i click on the other delete buttons from 2nd or 3rd row, there is no action.
Please suggest the correct path to sort out this problem.
Thanks in advance
Here is my code
<tr>
<td><?php echo $val['last4'];?></td>
<td><?php echo $val['exp_month'];?></td>
<td><?php echo $val['exp_year'];?></td>
<td><button id = "del">Delete</button></td>
</tr>
Ajax part
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$('#del').click(function() {
//var a=document.getElementById("").value;
var val0 = $('#id').val();
var val01 = $('#cust').val();
var fade = document.getElementById("fade");
var show = function(){
fade.style.display = "block";
}
show();
$.ajax({
type: 'POST',
url: 'mywebsite.com/deleting.php',
data: { card_id: val0,cust_id: val01 },
success: function(response) {
fade.style.display = "none";
// alert(response);
mystring = response.replace(/^\s+|\s+$/g, "");
$('#result11').html(mystring);
}
});
});
</script>
You have the same id on your buttons. Id's must be unique within the html document and can not be shared between multiple elements. Read more about the html id attribute
Change the button to use a class instead:
<td><button class="del">Delete</button></td>
Then change your jQuery to bind to that class instead:
$('.del').click(function(e) {
// Since we're using ajax for this, stop the default behaviour of the button
e.preventDefault();
// Get the value from the clicked button
var val0 = $(this).val();
I also added the event e in the function call, and stopped the default behaviour of the button (which is to submit the form) when it's clicked.
You need to give delete buttons a class and bind event on that class not with id. Then on bind function select values from that row elements and then pass them to Ajax.

jquery and ajax page refreshing issue

I am fetching a problem though I know it's not a big issue, but something is different to me as I new. I have a page which has a list of records, fetching from a database. Now one button is there , after clicking the records, one pop up will be opened up along with some data. Inside that pop up one another link is there called "restore", whenever , that linked will be clicked out the database has been updated. Now up to this its okay for me. But whenever, I close the pop up, my list of records should automatically changed as some records have been restored. But I am not getting the result until and unless I do not refresh the page. so how can I do this, please help me ....
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "restore-request-process.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
//return false;
});
});
in the restore-request-process.php page I just update the database and echo the id.
After the database update, call a function to update the front end or simply reload page using location.reload()
you need to have declared global function in parent window
function Update(){
//global function in parent, update div
}
on popup window call function
window.opener.Update();
that will automatic reload your div, and not all page, If it's not necessary
Suppose this is your listing format
<table>
<?php
foreach($results as $result) { ?>
<tr id="my_div">
<td><?php echo $result->name?></td>
<td class="delete" id="<?php echo $result->id?>"><img src="delete.png"/></td>
</tr>
<?php } ?>
</table>
In restore-request-process.php write a query which fetch all the result from database and just echo the result like this
$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '<td>'. echo $row["name"].'</td>
<td class="delete" id="'. echo $row["id"].'"><img src="delete.png"/></td>' ;
}
and onsuccess replaced all the content inside the my_div with response text
CODE IS NOT TESTED
for more references you can go through this link

Categories