Render table values dynamically using Ajax after page load in php - javascript

My idea is to get connectivity status of available servers in database on a php page.
<tbody>
<?php foreach ($data['servers'] as $server) { ?>
<tr>
<td class=""><?php echo $server->server_name; ?></td>
<td class=""><?php echo $server->base_path; ?></td>
<td class="server_status"><?php if (is_dir($server->base_path)){ echo 'Pass';} else { echo 'Fail' } ?></td>
</tr>
<?php } ?>
</tbody>
I want to do this just after page load using ajax like this page screenshot
How do I call ajax to get each value of this dynamically generated table. So far, I have tried the following code
<?php foreach ($data['servers'] as $server) { ?>
<tr>
<td class=""><?php echo $server->server_name; ?></td>
<td class=""><?php echo $server->base_path; ?></td>
<td class="server_status"></td>
<td class="server_status_loading"></td>
</tr>
<?php } ?>
JS
$(function(){
$(".server_status").hide();
$(".server_status_loading").show();
$.ajax({
url: 'get-server-status'
})
.error(function(){
alert('Error!');
})
.done(function(response){
$(".server_status_loading").hide();
$(".server_status").show();
$(".server_status").html(response);
});
get-server-status function:
public function getStatus() {
$basep = $this->_serverModel->getBasePath(2);
if (is_dir($basep)) {
echo 'Pass'; exit;
}
else {
echo 'Fail'; exit;
}
}
Thanks in advance!

first add id to your <tr>.
<?php foreach ($data['servers'] as $server) { ?>
<tr id="echo database id here.">
<td class=""><?php echo $server->server_name; ?></td>
<td class=""><?php echo $server->base_path; ?></td>
<td class="server_status"></td>
<td class="server_status_loading"></td>
</tr>
then check this link to handle the ajax on page load and this link to handle the ajax on click.Rest everything is provided there.
In link you can replace status to server_status_loading

try like this
$(document).ready(function(){
var hTable = document.getElementById('table2');
var iRowCount = hTable.rows.length;
for(var i=1; i<iRowCount; i++){
basepath= hTable.rows[i].cells[2].childNodes[1].value;
$.ajax({
url: 'get-server-status',
data :basepath
})
.error(function(){
alert('Error!');
})
.done(function(response){
hTable.rows[i].cells[2].childNodes[3].value=response;
});
}
}

Related

Display alert on button submission

So I have built a very basic application system. I have made one page where I can see all the applications in a table via MySQL query. I have also made so I can click a button to either approve or deny the application. Dependning on which button I press, the row with that specific user will be moved do the approved or denied table in the database. But, I want to display an alert when pressing the different buttons at the same time they send the row id to the PHP code.
Here is my code for the application table site: (register.php)
<?php
$query = "SELECT * FROM ansokningar";
$query_run = mysqli_query($link, $query);
?>
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th> ID </th>
<th> Förnamn </th>
<th>Efternamn </th>
<th>Mejladress</th>
<th>Ålder</th>
<th>Ansökt som</th>
<th>Läs Ansökning</th>
<th>Godkänn</th>
<th>Neka</th>
</tr>
</thead>
<tbody>
<?php
if(mysqli_num_rows($query_run) > 0)
{
while($row = mysqli_fetch_assoc($query_run))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['fornamn']; ?></td>
<td><?php echo $row['efternamn']; ?></td>
<td><?php echo $row['mejladress']; ?></td>
<td><?php echo $row['alder']; ?></td>
<td><?php echo $row['intresseradavyrket']; ?></td>
<td>
<form action="register.php" method="post">
<input type="hidden" id="deleteid" name="delete" value="<?php echo $row['id']; ?>">
<center> <button id="delete" type="submit" name="delete" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i></button></center>
</form>
</td>
</tr>
<?php
}
}
else {
echo $ingaansokning;
}
mysqli_close($link);
?>
And here is my PHP code for moving the row: (neka.php)
<?PHP require '../db/dbconfig.php';
if(isset($_POST['id']))
{
$id = $_POST['id'];
$query = "
INSERT INTO nekade SELECT * FROM ansokningar WHERE id='$id';
DELETE FROM ansokningar WHERE id='$id';
";
$query_run = $link->multi_query($query);
if($query_run)
{
$_SESSION['success'] = '';
header('Location: ../../register.php');
exit();
How do I send the row ID from the first page to the second and display one alert when it's done?
I have tried this on the first page (register.php) but it doesn't work:
<script>
$(function(){
$('#delete').click(function() {
var id = <?php echo $row['id']; ?>;
$.ajax({
type: 'POST',
url: 'includes/ansokningar/neka.php',
data:{id: id},
success: function(data){
Swal.fire(
'Grattis!',
'Din ansökan är nu skickad!',
'success'
)
}
})
})
});
(Without the ajax stuff it works to move the user to the other table)
Thanks!

AJAX event works but not reflect PHP MYSQL result simultaneously without refresh.

Hello guys I am new to AJAX and I'm developing DB list like CRUD and one of delete feature I used with AJAX actually it deletes record but only reflect after manual refresh not simultaneously so I need your help with AJAX.
List.php
<?php
include "db.php";
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
?>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(document).on('click','#btn_delete',function(){
var uid = $(this).data("id1");
if(confirm('Are You Sure To Delete '+uid+' ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//alert(data);
}
});
}
});
});
</script>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button calss="delete_btn" type="submit" id="btn_delete" name="delete" value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<!-- <a href="delete.php" data-id2="<?php echo $row->uid; ?>" id="delete" alt="DELETE" >Delete</a> -->
Update
</td>
</tr>
<?php } ?>
</table>
Whenever I press Delete button it actually delete record on first hand from database that mean ajax works but simultaneously table is not refresh, deleted entry remain in table till next refresh.
Delete.php
<?php
include "db.php";
$uid = $_POST['uid'];
$sql = "DELETE FROM users WHERE uid='".$uid."'";
$conn->query($sql);
$conn->close();
?>
<p id="check">Deleted</p>
I see some issues with this code and currently only partial or round about answers so I thought I would lend a hand :)
The dynamic rows you create inside your while loop have buttons that have a static ID across all delete buttons.
This could cause problems because ID's are supposed to be unique.
You misspelled class.
I removed the ID, corrected the spelling on class, and updated the JavaScript to use the button class instead of ID.
Since the button is in the table we can use it as a marker for which row to remove from the table.
This can be accomplished by calling closest: var tr = $(this).closest("tr");
Once the AJAX succeeds we can now remove that row: tr.remove();
The jQuery AJAX function has gone through some changes recently as the success callback was deprecated and then removed in 3.0 see Deprecation Notice.
This would cause your success call to not fire as it doesn't exist in 3.0 and from your question we can see that your using version 3.2.1.
I have replaced the callback with the updated call.
Here is the solution I came up with:
<script>
$(document).ready(function() {
$(document).on("click", ".btn_delete", function(){
var tr = $(this).closest("tr");
var uid = $(this).data("id1");
if (confirm("Are You Sure To Delete " + uid + "?")) {
$.ajax({
url: "delete.php",
type: "POST",
data: "uid=" + uid,
dataType: "text",
done: function(data){
tr.remove();
}
});
}
});
});
</script>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button class="delete_btn" type="submit" name="delete"
value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<a href="form.php?link=<?php echo $row->uid; ?>"
value="<?php echo $row->uid; ?>" alt="UPDATE">Update</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
On another note the PHP call to your MySql in Delete.php is susceptible to injection attacks here is some documentation on that in PHP < 5.5 see Example 5.50 An example SQL Injection Attack and in PHP >= 5.5 as the function was deprecated in 5.5.
You can delete the element in the success callback function like so:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//if using jquery
//$('tr').filter(':has(td:first:contains(' + uid + '))').remove();
$('tr').filter(function() {
return $(this).find('td:first').text() == uid;
}).remove();
//if not
var table = document.getElementsByTagName('table')[0];
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].textContent == uid) {
table.removeChild(rows[i]);
}
}
}
});
You can use this:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
window.location.href = 'YOUR PAGE';
}
})
You can make the page to reload automatically after successful ajax call. Try This:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
location.reload();
}
})

How to create array in document.getElementById

AS title, I want to create array in document.getElementById because my id is come from repeat region. Below is my javascript and html.
<script type ="text/javascript">
$(document).ready(function(){
$('table tbody tr').click(function(){
var PurchaserID = window.opener.document.getElementById("PurchaserID");
var n = 5;
PurchaserID.value = document.getElementById("test[n]").innerText;
alert(PurchaserID.value);
window.close();
});
});
</script>
<?php do { ?>
<tr>
<td id = "test[<?php echo $row_Purchaser['ID'];?>]" align="center" ><?php echo $row_Purchaser['ID'];?></td>
<td align="center"><?php echo $row_Purchaser['Name']; ?></td>
<td align="center"><?php echo $row_Purchaser['IC']; ?></td>
<td align="center"><?php echo $row_Purchaser['Handphone']; ?></td>
</tr>
<?php } while ($row_Purchaser = mysql_fetch_assoc($Purchaser)); ?>
Any problem of my program. Why I can't get the value test[n] to test[5] even I create var n =5; May I know how to solve it. Thanks if you could me !!

How to get values dynamically in js from php?

I want to get dynamic values from php in js in a dynamic manner...Let me elaborate: First I show the image then code:
<div id="">
<table border="1" width="820" style="margin-left:15px;">
<tr>
<th>Sr #</th>
<th>Commented Post</th>
<th>Commenter Name</th>
<th>Commenter Email</th>
<th>Comments</th>
<th>Status</th>
</tr>
<?php
$values = array();
while($row= mysqli_fetch_assoc($res)) {
$values[] = $row['comment_id'];
?>
<tr align="center" style="height:50px;">
<td><?php echo $row['comment_id']; ?></td>
<td><?php echo $row['post_title']; ?></td>
<td><?php echo $row['comment_name']; ?></td>
<td><?php echo $row['comment_email']; ?></td>
<td><?php echo $row['comment_text']; ?></td>
<td>
<?php
if($row['status']==0) { ?>
<div class="status_<?php echo $row['comment_id']; ?>" id="status_<?php echo $row['comment_id']; ?>">Unapproved</div>
<?php } else { ?>
Approved
<?php } ?>
</td>
</tr>
<?php }
?>
</table>
</div>
And Js here's:
<script type="text/javascript">
$(document).ready(function(){
var values = <?php echo json_encode($values); ?>;
var id = values[0];
$('.status_'+id).click(function(){
$("#status_"+id).html("<b>Test</b>");
});
var i = values[1];
$('.status_'+i).click(function(){
$("#status_"+i).html("<b>Test</b>");
});
});
</script>
I want to get all comment id's in js dynamically, so that on clicking each row link, it changes to text "Test"...As I have written the js code manually...how we obtain all the comment_id's dynamically in js..I hope you got the idea what I am trying to do...
There's no point in assigning unique ids to each of your elements. Why not do something like:
<tr>
<td>...</td>
<td><a href="#" onclick="toggle(this, <?php echo $id ?>)">Unapproved</td>
</tr>
then something like
function toggle(node, id) {
node.parentNode.innerHTML = '<b>test</b>';
... do something with "id" value? ...
}
No need for getElementById, assigning a massive pile of repetitive ids, etc.. just a single function call and a bit of DOM tree traversal.
Try to add a class to your status TD, like <td class="status" data-id="<?php echo $row['comment_id'] ?>">// your inital value</td>.
Using jQuery you can easily listen for events which are attached to a an event listener:
$(document).on('click', '.status', function() {
var id = $(this).attr('data-id');
$(this).html('<strong>Test</strong>');
// maybe to something with ajax?
$.ajax({
url: 'yourfile.php?call=doSomething&id=' + id,
type: 'post'
}).done(function(response) {
// console.log(response);
});
});
You dont appear to actually use the ids.
All you need to do is ascertain the clicked element, which use can do using this
html:
<div class="status">Unapproved</div>
js:
$(document).ready(function(){
$('.status').click(function(){
$(this).html("<b>Test</b>");
});
});

Cart is updated only once using Jquery and Codeigniter

I am working on Updating Codeigntier Cart with Jquery using Ajax call to update. Here is my jquery function
$(function() {
$('.cart_form select').on('change', function(ev) {
var rowid = $(this).attr('class');
var qty = $(this).val();
var postData_updatecart = {
'rowid' : rowid,
'qty' : qty
};
//posting data to update cart
$.ajax({
url : base_url + 'bookings/update_booking_cart',
type : 'post',
data : postData_updatecart,
beforeSend : function() {
$('#cart_content').html('Updating...');
},
success : function(html) {
//window.location.href = "postproperty.php?type="+suffix+'&page=page1';
$('#cart_content').html(html);
}
});
});
});
I have cart view file as
<div class="cart_form">
<?php echo form_open(base_url().'index.php/bookings/customerdetails', array('class' => 'bookings_form_customer', 'id' => 'bookings_form_customer')); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
<tr>
<th style="text-align:left">Item Description</th>
<th style="text-align:left">QTY</th>
<th style="text-align:right">Item Price</th>
<th style="text-align:right">Sub-Total</th>
</tr>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
<tr>
<td>
<?php echo $items['name']; ?>
<?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
<p>
<?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />
<?php endforeach; ?>
</p>
<?php endif; ?>
</td>
<td>
<select name="<?php echo $i.'[qty]'; ?>" class="<?php echo $items['rowid']; ?>">
<?php
for($tt=0; $tt<=10; $tt++)
{
?>
<option value="<?php echo $tt; ?>" <?php if($tt==$items['qty']) echo 'selected="selected"'; ?>><?php echo $tt; ?></option>
<?php
}
?>
</select>
</td>
<td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
<td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="2"> </td>
<td class="right"><strong>Total</strong></td>
<td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>
</table>
<p><?php echo form_submit('update_cart', 'Update your Cart'); ?></p>
</form>
</div>
Things are working Nice. But, lets say if I have 2 products, if i select one item's qty from 1 to 2, cart is updated and updated cart is shown using AJAX. But, if I immediately change another item's qty then it doesnt work.
The cart view file is inside class 'cart_form'.
Helping hands are appreciated.
I got an answer. You can refer below link
Ajax Request works only once
OR
Directly follow this
REPLACE jquery code part by
$(function() {
$(document).on( "change", "#bookings_form_customer select", function(ev) {
// your code goes here
});
});

Categories