How i can refresh a part of page using javascript - javascript

I try to filter information, but I only need that just the table refresh and display the information using javascript, and I can not find a good method to do it
I try to use this code for my page, but I dont know how to implement it
JS
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.style.visibility= "hidden";
dynamicPart.innerHTML="Loading..."
dynamicPart.innerHTML=await(await fetch(url)).text();
setTimeout(refresh,2000);}
HTML of the metod
HTML
<div id="staticPart">Here is static part of page
<button id="btn" onclick="refresh()">Start refreshing (2s)</button>
</div>
<div id="dynamicPart">Dynamic part</div>
And this is my table in Html
<div class='d-flex justify-content-center' id="contentTable">
<table class='table table-stripped' border=1 id="table">
<thead class= 'thead-dark'>
<tr>
<th>#</th>
<th>Fecha</th>
<th>Documento</th>
<th>Nombres</th>
<th>Apellidos</th>
<th>Sede</th>
<th>Siglas</th>
<th>Administrador</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i < count($datos); $i++){
$id = $datos[$i]['id_controlAsis'];
$rutaEd = "/Jomar/users_control/controller/ControlAsisController.php?action=editar&id_controlAsis=$id";
$rutaEl = "/Jomar/users_control/controller/ControlAsisController.php?action=eliminar&id_controlAsis=$id";
echo "<tr>";
echo "<td>". ($i+1) ."</td>";
echo "<td> {$datos[$i]['fecha']} </td>";
echo "<td> {$datos[$i]['documento']} </td>";
echo "<td> {$datos[$i]['nombres']} </td>";
echo "<td> {$datos[$i]['apellidos']} </td>";
echo "<td> {$datos[$i]['sede']} </td>";
echo "<td> {$datos[$i]['siglas']} </td>";
echo "<td> {$datos[$i]['administrador']} </td>";
echo "<td>
<a href='$rutaEd' class='badge badge-primary'>Editar </a>
<a href='$rutaEl' class='badge badge-warning'>Eliminar </a>
</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
Thanks for the help, sorry for my English

Making a lot of assumptions. You need to define the 'btn' and 'dynamicPart' variables before you use them.
Example:
let btn = document.querySelector("#id_of_some_button_in_html");
let dynamicPart = document.querySelector("#id_of_a_div");
Then you just need to call
refresh();
then the
setTimeout(refresh,2000);
of your code will run every 2 seconds.
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
let btn = document.querySelector("#id_of_some_button_in_html");
let dynamicPart = document.querySelector("#id_of_a_div");
btn.style.visibility= "hidden";
dynamicPart.innerHTML="Loading..."
dynamicPart.innerHTML=await(await fetch(url)).text();
setTimeout(refresh,2000);}
refresh();
Understanding this is not considered 'good' code, but I am making the assumption that you are just starting to learn JS and this code is not something that will be put into production.

Related

Post recordset to a table, then select one row and post to another page

I recently ran into a problem I wasn't quite sure how to solve. Sharing it here in case it helps someone else.
Use Case: User enters a string in a search box on a PHP page. On submit, the page queries the database and then posts results to a table on the same page. User then selects a single record with a radio button and needs to post only that record to a different PHP page. The second page does not have access to the database.
I took the actual page and created a sample page for clarity and testing, since the original had about 15 table columns.
<div class="container">
<div class="row" style="margin-top: 1rem;">
<div class="col-sm">
<form action="" method="post">
<table class="fit" id="entry">
<tr>
<td class="fit"><label for="start">Planet (try <strong>Caprica</strong> or <strong>Picon</strong>): </label></td>
</tr>
<tr>
<td class="fit"><input type="test" id="planet" name="planet" required autofocus /></td>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Get Characters" />
</form>
</div>
</div>
</div>
<div class="container" style="margin-top: 2rem;">
<div class="row">
<div class="col-sm">
<?php
require_once('./resources/pdo.php');
if ( isset($_POST['planet']) ) {
$planet = strtolower($_POST['planet']);
$pdo = new myPDO('phppostpost');
try {
$stmt = $pdo->prepare('CALL devCharacters(?)');
$stmt->bindParam(1, $planet, PDO::PARAM_STR);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred: " . $e->getMessage());
}
?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th class="fit">Select</th>
<th class="fit" scope="col">Customer First</th>
<th class="fit" scope="col">Customer Last</th>
<th class="fit" scope="col">Planet</th>
</tr>
</thead>
<tbody>
<?php while ($r = $stmt->fetch()): ?>
<tr>
<?php echo "<td class='fit'><input type='radio' id='cust-" . $r['customer_id'] ."' name='cust-id' value='". $r['customer_id'] . "' </td>"; ?>
<?php echo "<td class='fit'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['origin_planet'] . "</td>"; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<input class="btn btn-primary" onclick="getSelectedRowData();" type="submit" value="Send" />
<?php } ?>
</div>
</div>
</div>
As a relatively new developer, I couldn't figure out how to (1) grab just the selected row and (2) post data on submit from just that row, rather than from the the original search form.
After much Googling, as well as a kick in the pants from a Stack Overflow user who reminded me I needed to actually research for more than 20 minutes (thank you!), I was able to solve it.
I'll post the answer below for anyone else who runs into a similar problem.
To solve this, I used JavaScript to grab the selected row. In order to efficiently grab the correct record, I updated each TD element to have a unique, dynamically-generated ID:
<?php echo "<td class='fit' id='fname-" . $r['customer_id'] ."'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='lname-" . $r['customer_id'] ."'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='planet-" . $r['customer_id'] ."'>" . $r['origin_planet'] . "</td>"; ?>
I also gave the table body an ID so I could grab it quickly without grabbing a parent, then children, etc.:
<tbody id="results-body">
Finally, here's the JavaScript.
function getSelectedRowData() {
const tableRowArray = Array.from([document.getElementById('results-body')][0].rows);
let custFirst;
let custLast;
let custPlanet;
tableRowArray.forEach((tableRow, i) => {
cellButton = tableRow.getElementsByTagName('input');
if (cellButton[0].checked == true ) {
const rowID = cellButton[0].id.split('-').pop();
custFirst = document.getElementById('fname-' + rowID).innerHTML;
custLast = document.getElementById('lname-' + rowID).innerHTML;
custPlanet = document.getElementById('planet-' + rowID).innerHTML;
}
});
/* Build a hidden form solution to prep for post.
Source: https://stackoverflow.com/questions/26133808/javascript-post-to-php-page */
let hiddenForm = document.createElement('form');
hiddenForm.setAttribute('method', 'post');
hiddenForm.setAttribute('action', 'newpage.php');
hiddenForm.setAttribute('target', 'view');
const fieldCustFirst = document.createElement('input');
const fieldCustLast = document.createElement('input');
const fieldCustPlanet = document.createElement('input');
fieldCustFirst.setAttribute('type', 'hidden');
fieldCustFirst.setAttribute('name', 'custFirst');
fieldCustFirst.setAttribute('value', custFirst);
fieldCustLast.setAttribute('type', 'hidden');
fieldCustLast.setAttribute('name', 'custLast');
fieldCustLast.setAttribute('value', custLast);
fieldCustPlanet.setAttribute('type', 'hidden');
fieldCustPlanet.setAttribute('name', 'custPlanet');
fieldCustPlanet.setAttribute('value', custPlanet);
hiddenForm.appendChild(fieldCustFirst);
hiddenForm.appendChild(fieldCustLast);
hiddenForm.appendChild(fieldCustPlanet);
document.body.appendChild(hiddenForm);
// Post
window.open('', 'view');
hiddenForm.submit();
}
This worked for me, but I'm sure there's a better way to do this. Hopefully this (1) helps someone else and (2) a better solution is posted!
Here's a working demo: https://postfrompost.paulmiller3000.com/
Full source here: https://github.com/paulmiller3000/post-selected-from-post

How to pass information through jQuery

I am attempting to pass information from the button within the column "actions" to the modal div, I call the modal using JS, However I am unsure about how to send information from the table over to the div. (Remember it has to be different information for every button as each button is in another row)
<?php
error_reporting(0);
$con = new mysqli("localhost","****","****","****");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
$cuser = $_COOKIE['c_user'];
$result = $con->query("SELECT * FROM calls");
echo"
<table class=\"table table-bordered responsive\">
<thead>
<tr>
<th width=\"5%\">#</th>
<th>Call Status</th>
<th>Player ID</th>
<th>Player Name</th>
<th width=\"33%\">Actions</th>
</tr>
</thead>
<tbody>";
while($row = $result->fetch_assoc()){
echo "<tr> ";
echo("<td>" . $row['id'] . "</td> ");
echo("<td>" . $row['status'] . "</td> ");
echo("<td>" . $row['pid'] . "</td> ");
echo "<td>" . $row['pname'] . "</td> ";
echo "<td> ";
if($row['status'] == 'Pending'){
echo "<a button type=\"button\" class=\"btn btn-warning\" href=\"calls.php?claim=true&callid=$row[id]\">Claim Call</button /a> ";
} else if($cuser == $row['claimedby']) {
echo "<a button type=\"button\" class=\"btn btn-danger\" href=\"calls.php?closecall=true&callid=$row[id]\">Close Call</button /a> ";
} else {
echo "<a button type=\"button\" class=\"btn btn-warning disabled\">Claimed</button /a> ";
}
echo "<a button type=\"button\" href=\"javascript:;\" onclick=\"jQuery('#modal-2').modal('show');\" class=\"btn btn-info\">Call Info</button /a> ";
echo "<a button type=\"button\" id = $row[id] href=\"javascript:;\" onclick=\"jQuery('#modal-1').modal('show');\" class=\"btn btn-success\">Server Info</button /a> ";
echo "<a button type=\"button\" class=\"btn btn-primary\">Join Server</button /a> ";
echo "</td> ";
}
echo "</tr>
</tbody>
</table>";
echo"<div class=\"modal fade\" id=\"modal-1\">
<div class=\"modal-dialog\" style=\"width: 50%\">
<div class=\"modal-content\">
<div class=\"modal-header\">
<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>
<h4 class=\"modal-title\">Call Info</h4>
</div>
<div class=\"modal-body\" id=\"serverHandle\">
</div>
<div class=\"modal-footer\">
<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>
</div>
</div>
</div>
</div>";
?>
Do you want to send any kind of information from Buttons to Modal DIV when somebody clicks on those buttons ? If that you want then you can add one custom attribute to your button like this <button info='my-info' id=''>Click</button> then when someone click on that button you can extract the value from that attribute by using JavaScript this & place that to the MODAL window by using any ID from Modal DIV.
You can add something like this to your button along with a click event.
data-value="<?php echo $Something->SomeValue;?>"
Then, when the click event gets triggered, you can get the value like this:
$(this).data("value");
you can use various data-[tag] to pass multiple pieces of information.
Or as an alternative, add this to each button:
onclick='someFunction("<?php echo $Something->SomeValue;?>")';

How to use jquery to loop through table rows echoed by php and select a specific row where a property is meet

I have a table dynamically created from a Mysql database. I am trying to create a modal dialog whereby if a user clicks on the view button a pop-up is displayed showing the values of that specific row. How do I loop through the table and select a specific row using jquery? I am using a Javascript library called bootbox.js I am able to display the pop-up however I cant get it to display the relevant row, it instead displays only the first row. The relevant PHP and the Javascript code I tried is shown below
echo "<table class='table table-hover table-responsive table-bordered'>";
echo "<tr>";
echo "<th>Payment Supplier</th>";
echo "<th>Payment Reference</th>";
echo "<th>Payment Cost rating</th>";
echo "<th>Payment Amount</th>";
echo "<th>Actions</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$payment_supplier}</td>";
echo "<td>{$payment_ref}</td>";
echo "<td>{$payment_cost_rating}</td>";
echo "<td>{$payment_amount}</td>";
?>
<div id="dom-target" style="display: none;">
<?php
$output = $payment_supplier; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<?php
echo "<td>";
echo "<a view-id='{$payment_id}' class='btn btn-default view-object'>View</a>";
echo "<a href='lib/Local/update_payment.php?id={$payment_id}' class='btn btn-default left-margin'>Edit</a>";
echo "<a delete-id='{$payment_id}' class='btn btn-default delete-object'>Delete</a></div>";
echo "</td>";
echo "</tr>";
$x++;
}
echo "</table>";
The Javascript code is
<script>
$(document).on('click', '.view-object', function(e) {
var div = document.getElementById("dom-target");
var myData = div.textContent;
bootbox.alert(myData, function() {
console.log("Alert Callback");
});
});
</script>
What am I missing here or is there a better way to achieve this?
As you had told , your code displays only the first row.
This is because you have not set different unique id to each row div to show on click of view.
Try using the code as :
echo "<table class='table table-hover table-responsive table-bordered'>";
echo "<tr>";
echo "<th>Payment Supplier</th>";
echo "<th>Payment Reference</th>";
echo "<th>Payment Cost rating</th>";
echo "<th>Payment Amount</th>";
echo "<th>Actions</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$payment_supplier}</td>";
echo "<td>{$payment_ref}</td>";
echo "<td>{$payment_cost_rating}</td>";
echo "<td>{$payment_amount}</td>";
//SET THE UNIQUE ID OF DIV TO SHOW ON CLICK OF VIEW//
?>
<div id="dom-target-<?php echo $payment_id;?>" style="display: none;">
<?php
$output = $payment_supplier; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<?php
echo "<td>";
echo "<a view-id='{$payment_id}' class='btn btn-default view-object'>View</a>";
echo "<a href='lib/Local/update_payment.php?id={$payment_id}' class='btn btn-default left-margin'>Edit</a>";
echo "<a delete-id='{$payment_id}' class='btn btn-default delete-object'>Delete</a></div>";
echo "</td>";
echo "</tr>";
$x++;
}
echo "</table>";
JS :
<script>
$(document).on('click', '.view-object', function(e) {
selectedId=$(this).attr('view-id'); //GET SELECTED ROW ID FROM ANCHOR TAG
var div = document.getElementById("dom-target-"+selectedId); //CALL THE SELECTED ROW DIV TO POP UP
var myData = div.textContent;
bootbox.alert(myData, function() {
console.log("Alert Callback");
});
});
</script>
This may helps you.
try this...
<script>
$(document).on('click', '.view-object', function(e) {
bootbox.alert($(this).val(), function() {
console.log("Alert Callback");
});
});
</script>
There are two main problems with your script:
You are recycling the dom-target ID. Remember that IDs have to be unique in your HTML document. You can change it from ID to a class instead.
<div> is not a valid child of <tr>. Browsers will attempt to fix this, which might involve the element being removed from the table, or sequestered in a <td>.
Your function lacks context — when .view-object is clicked on, you need to reference to the current element where the event originated from. Using $(this) will point you in the right direction.
I suggest that you store the value in dom-output as a HTML5 data- attribute associated with the specific row, i.e., instead of:
echo "<tr>";
echo "<td>{$payment_supplier}</td>";
echo "<td>{$payment_ref}</td>";
echo "<td>{$payment_cost_rating}</td>";
echo "<td>{$payment_amount}</td>";
?>
<div id="dom-target" style="display: none;">
<?php
$output = $payment_supplier; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
use:
echo "<tr data-domtarget='".htmlspecialchars($payment_supplier)."'>";
echo "<td>{$payment_supplier}</td>";
echo "<td>{$payment_ref}</td>";
echo "<td>{$payment_cost_rating}</td>";
echo "<td>{$payment_amount}</td>";
?>
You can use the following script:
$(document).on('click', '.view-object', function() {
var domTarget = $(this).closest('tr').data('domtarget');
bootbox.alert(domTarget, function() {
console.log("Alert Callback");
});
});

Expand/Collapse table row Javascript works wrongly

I'm using this code to expand database table row to reveal more information about the item, but it does exactly the opposite.
$("td span.expand").click(function() {
$(this).parents("tr.main").nextUntil("tr.main"). toggle();
});
When I open the table all rows that must be hidden are being shown and if I click on any main row it will hide that rows.
How to invert this?
Here's part of code I use for table (I know, it's messy):
echo '<table border="1" class="tabula">
<tr class="main">
<th width="30px">Nr.</th>
<th width="75px">Mašīnas numurs</th>
<th width="75px">Reģistrācijas numurs</th>
<th width="75px">Marka / Modelis</th>
<th width="75px">ID</th>
</tr>';
//Ieraksta datus tabulā
while($row = mysql_fetch_array($query))
{
echo "<tr class='main'>";
echo "<td width='30px'>" . $row['nr'] . "</td>";
echo "<td width='75px'>" . $row['numurs'] . "</td>";
echo "<td width='75px'><span class='expand'>" . $row['regnr'] . "</span></td>";
echo "<td>" . $row['modelis'] . "</td>";
echo "<td>" . $row['apzim'] . "</td>";
echo "</tr>";
echo "<tr class='hidden'>";
echo "<td>text</td>";
echo "<td>text</td>";
echo "<td>text</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
Try using CSS in your file and include the following:
<style>
.expand
{
display:none;
}
</style>
I use a jQuery-based toggle script, and that's what I used when I had a similar problem such as this.
You may need to use .hidden { display:none; } instead.

Javascript popup only showing the last result in PHP query

I have the following block of code and I'm not sure how to do what I'm wanting to do.
In essence I'm wanting the javascript popup to display that row's value, but (obviously) it's only showing the final row of data as the popup isn't set for each row but rather calls the variable when clicked.
Any help would be appreciated!
<?php
$result = mysql_query("SELECT hr_overtime.overtime_id, hr_user.name, hr_overtime.overtime_date, hr_overtime.overtime_type, hr_overtime.overtime_from, hr_overtime.overtime_to, hr_overtime.overtime_amount, hr_overtime.details
FROM hr_overtime
inner join hr_user
on hr_user.user_id = hr_overtime.user_id
where hr_overtime.overtime_status = 'Pending' order by hr_overtime.overtime_date ASC");
echo "
<table border='0'>
<tr>
<th class='tablecell_header'>Consultant</th>
<th class='tablecell_header'>Date</th>
<th class='tablecell_header'>Type</th>
<th class='tablecell_header'>From</th>
<th class='tablecell_header'>To</th>
<th class='tablecell_header'>Amount</th>
<th> </th>
<th> </th>
<th> </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$work = $row['details'];
echo "<tr>";
echo "<td class='tablecell'>" . $row['name'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_date'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_type'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_from'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_to'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_amount'] . "</td>";?>
<td class='tablecell'> <button onclick="myFunction()">Show work</button> </td><script>
function myFunction()
{
alert("<?php echo $work;?>");
}
</script>
<?php
echo "<td valign='middle'><form action='manager_overtime_approve.php' method='post'>
<input name='approve_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='APPROVE' id='edit' />
</form></td>";
echo "<td valign='middle'><form action='manager_overtime_reject.php' method='post'>
<input name='cancel_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='REJECT' id='edit' />
</form></td>";
echo "</tr>";
}
echo "</table>";
?>
There is no need for a separate function which you are using incorrectly. You can simply use an inline alert for this:
<td class='tablecell'> <button onclick="alert('<?php echo $work;?>');">Show work</button>
You can't insert the declaration of myFunction() inside your foreach loop, that way you are overriding for each entry the behaviour showed thus it's only working for the last row.
one fast solution would be to insert the whole $work variable as an argument of your onclick function eg.
<td class='tablecell'> <button onclick="myFunction('<?php echo $work ?>')">Show work</button>
and then outside of the foreach loop you can define myFunction such as:
function myFunction(details){
alert(details)
}
I think, in result HTML you have a multiple definitions of myFunction() and javascript uses only last one. You can use a HTML tag attributes to show right information.
try this
$work .= $row['details'];
and set javascript out of the loop
good luck
That's because myFunction is a Javascript function, which is defined once and doesn not share the same scope as PHP. So $work hold just the last value.
I'd suggest something like this:
echo "<tr data-detail-value='$work'>";
...
<td class='tablecell'> <button onclick="myFunction(this)">Show work</button>
...
function myFunction(btn) {
alert(btn.parentNode.parentNode.getAttribute("data-detail-value"));
}

Categories