How to get values dynamically in js from php? - javascript

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>");
});
});

Related

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 !!

Render table values dynamically using Ajax after page load in php

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;
});
}
}

HTML, JQuery seporation of loading divs

I currently have a page that loads slow and would like to make the user experience more enjoyable. I would like to load each div so when a div is read() fade in using jQuery. Currently my code works but it loads everything at the same time and fades in. I would like it to load in order of div placement. Below is an example code of loading 2 divs with large tables in them. I would like each table to show up as soon as it's ready. The first one should be ready before the second one and it should render first. I have tried to separate the js so that each has their own ready() but that didn't work.
Also: I am more looking for a consent on how to do this rather than the specific code. What if I have a lot of divs with a lot of different tables. Not every div will have a table in it. some might have pictures or just text. There should be a way to load each div whenever it's ready to be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="style/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="style/main.css" rel="stylesheet" type="text/css" />
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<title>Animated jQuery Fade | Script tutorial</title>
</head>
<script>
$(document).ready(function(){
$('.myTable').DataTable();
});
$(document).ready(function(){$(".content").hide().fadeIn(1000);});
</script>
<body>
<div id="header">
<h1>Welcome to test page</h1>
</div>
<div class="content" style="display: none;">
<table class="myTable">
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
</thead>
<tbody>
<?php for($i =0; $i <10000; $i++){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="content" style="display: none;">
<table class="myTable">
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
</thead>
<tbody>
<?php for($i =0; $i <20000; $i++){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
I think what you need here is to provide you DataTables with an AJAX source, which will retrieve your data. Then set a callback that will fire when the data has been loaded to fadeIn your tables.
It might look something like this:
$(document).ready(function() {
$('#myTable1').dataTable( {
"ajax"{
"url": 'path/to/datasource.php',
"success" : function(){
$('#myTable1').parent().fadeIn(1000);
}
}
} );
} );
This is untested code and the syntax may be wrong, but it should give you an idea of how this is done. Also, the returned data from your php datasource must return json in the correct format DataTables is expecting (this is very important, and is often where people make mistakes).
Please see the DataTables ajax docs here.
the problem is not about what type of data it need to display, but rather you should limit amount of data display each time, and separate the server side, from client side, so it will reduce load on browser, the code below is untested, prob lot of syntax error #_#
PHP
<?php
// you can manual hard code the data, or use database, it really didn't matter what the data are it can be path of image, text, etc...
var $textData = array(); // eg ('text1','text2')
var $imgData = array(); // eg ('path/img.jpg', 'path/img.jpg')
var $divData = array(); // eg ('<div class="parent"><div class="child"></div></div>')
// see what data set you want to get
if($_POST['type']==='text') {
// now encode the data into json for ajax
echo json_encode($textData);
} else if($_POST['type']==='img') {
echo json_encode($imgData);
}
?>
JQUERY AJAX
<script>
if(some condition are made) {
$.ajax({
url: "text.php",
type: "POST",
data: {
type: 'text' // it can be anything
},
dataType: "JSON",
success: function (dataSet) {
// jquery to append dataSet, use if() to append to different place depend on type
// this set you can hide as default with css
// after data loaded fade in with jquery.
}
});
}
</script>

How to pass the id from each row of a loop table using jquery when edit button is click?

I have a table that displays all the data from my database and I've added a new column for edit button on each row so that this would update the data from my database when the user click a certain button he wants to update.
I have this code to loop through the data and display in a tabular format in my page:
<!--############## TABLE HEADER ##############-->
<thead>
<tr>
<th>Dummy ID</th>
<th>Date</th>
<th>NCA Balances</th>
<th>Account</th>
<!-- Update Button on each row -->
<th style="text-align:center;">Update</th>
</tr>
</thead>
<!--##########################################-->
<!--############# TABLE CONTENT ##############-->
<tbody>
<?php
$s1 = mysql_query("SELECT * FROM nca_totals");
while($row = mysql_fetch_array($s4)) {
$db_id = $row['total_id'];
$db_date = $row['nca_date'];
$db_balance = $row['nca_total'];
$db_account = $row['account_type'];
?>
<tr>
<!-- Input fields to be hidden just to get the ID value -->
<td><input type="text" id="total_id" value="<?php echo $db_id ?>"></td>
<td><?php echo $db_date ?></td>
<td><?php echo number_format($db_balance,2) ?></td>
<td><?php echo $db_account ?></td>
<td style="text-align:center;">
<button type="button" id="btn-update">Update</button>
</td>
</tr>
<?php } ?>
</tbody>
<!--##########################################-->
I want to use Ajax in jQuery so that when the user click the button update, the page does not have to reload. But first, I want to confirm that I get exactly the ID on each row and pass it to my jquery function like this:
update_nca.js
$(document).ready(function(){
// Get the values
$("#btn-update").click(function(){
var total_id = $("#total_id").val();
alert(total_id);
});
});
When I click the first button on the first row, It gets the ID from my table. But on the next row as well as the other row, no ID has been pass into my jquery. It doesn't get any value from my dummy textbox. Please help me improve my codes. Any help would be appreciated. Thanks
you are sharing the same ID to multiple inputs which makes a problem! I think you better use a class instead or remove it.
<tr>
<!-- Input fields to be hidden just to get the ID value -->
<td><input type="text" class="total_id" value="<?php echo $db_id ?>"></td>
<td><?php echo $db_date ?></td>
<td><?php echo number_format($db_balance,2) ?></td>
<td><?php echo $db_account ?></td>
<td style="text-align:center;">
<button type="button" class="btn-update">Update</button>
</td>
</tr>
$(".btn-update").click(function(){
var total_id = $(this).closest('tr').find('.total_id').val();
alert(total_id);
});
Id should be unique in any HTML document. You can use classes to represent the identity. Change id="total_id" to class="total_id". And id="btn-update" to class="btn-update".
Then, use this code to get the value from the total-id input.
$(".btn-update").click(function(){
var total_id = $(this).parent().parent().find(".total_id").val();
alert(total_id);
});
BTW way, $(this) represented the element that's taking the event, in this case the update button.
I suggest you pass the db_id value to a data- attribute, perhaps named data-db-id. Since each <tr> represents a record, place the data-db-id attribute on each <tr> element. Then with jQuery, retrieve the value of the data- attribute with the .data method: var id = $(this).data('db-id'). See complete example below:
<?php
$s1 = mysql_query("SELECT * FROM nca_totals");
while($row = mysql_fetch_array($s4)) {
$db_id = $row['total_id'];
$db_date = $row['nca_date'];
$db_balance = $row['nca_total'];
$db_account = $row['account_type'];
?>
<tr data-db-id="<?= $db_id ?>">
<td><?= $db_date ?></td>
<td><?= number_format($db_balance,2) ?></td>
<td><?= $db_account ?></td>
<td style="text-align:center;">
<button class="btn-update">Update</button>
</td>
</tr>
<?php } ?>
</tbody>
<script>
$('table').on('click', '.btn-update', function() {
var id = $(this).closest('tr').data('db-id');
// do something with the id....
});
</script>
Note a few changes:
This example uses the short PHP echo syntax (<?= $foo ?>).
Event delegation is used here. Read more here.
As others have already said, keep your id attribute values unique. (i.e., switch id="btn_update" in your loop to `class="btn_update")

How to get value table row value using jquery/ajax

<?php
include "config.php";
// Fetch the data
$con = mysql_query("select * from product");
?>
<div style=" height:250px; overflow:auto;">
<table class="table table-striped table-bordered dTableR" id="ajxtable">
<tr>
<th>Jobno</th>
<th>Product</th>
<th>Qty</th>
<th>Designed by</th>
<th>Action</th>
</tr>
<?php
while ($row = mysql_fetch_array($con)) {
$id = $row['id'];
$pcode = $row['pcode'];
$lproduct = $row['lproduct'];
$mrprate = $row['mrprate'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $lproduct; ?></td>
<td><?php echo $mrprate; ?></td>
<td><?php echo "admin"; ?></td>
<td><input type="button" id="addmorePOIbutton1" style="width:25px;" value="+" onClick=""/>
<input type="button" id="delPOIbutton1" style="width:25px;" value="-" onClick=""/></td>
</tr>
<?php
}
?>
</table>
</div>
This is ajax page. Below table is auto refreshed every 5 seconds.
My doubt is how to get that particular row value.
When i click table row + button, get these particular row values, and place to index page text box and this '+' button also hide.
Kindly suggest any jquery or ajax code for adding below code.
I am new to jquery ,,anybody help me with sample code..that would help me greately. Thanks in advance
$(document).ready(function () {
$('#yourtablename tr').click(function (event) {
alert($(this).attr('id')); //trying to alert id of the clicked row
});
});
Above code may be help you and another solution is:
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});

Categories