How to pass information through jQuery - javascript

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;?>")';

Related

How i can refresh a part of page using 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.

I want to change color of text in a table loop based on text value

I have a looped table displaying the results of a drop-down form post (lotstatus). I want to be able to change the color of the text based on the value they selected in the form.
if($result = mysqli_query($conn, $sql)){ if(mysqli_num_rows($res) > 0){ echo "
<table class='table table-bordered table-striped' width='100%' data-pagination='true' data-search='true'>"; echo "
<thead>"; echo "
<tr>"; echo "
<th>Status</th>"; echo "
<th>Street #</th>"; echo "
<th>Street Name</th>"; echo "
<th>City</th>"; echo "
<th>Parcel ID</th>"; echo "
<th>Lot # (Unit)</th>"; echo "
<th>Contract Signed Date</th>"; echo "
<th>Closing Date</th>"; echo "
<th>Action</th>"; echo "</tr>"; echo "</thead>"; echo "
<tbody>"; while($row = mysqli_fetch_array($res)){ echo "
<tr>"; echo "
<td>" . "
<div class='statuscolor'>". $row['lotstatus'] . "</div>". "</td>"; echo "
<td>" . $row['streetnumber'] . "</td>"; echo "
<td>" . $row['streetname'] . "</td>"; echo "
<td>" . $row['city'] . "</td>"; echo "
<td>" . $row['parcelid'] . "</td>"; echo "
<td>" . $row['lotnumber'] . "</td>"; echo "
<td>" . $row['contractsigneddate'] . "</td>"; echo "
<td>" . $row['closingdate'] . "</td>"; echo "
<td>"; echo "<a class='btn btn-info mr-2 mt-2' href='readLot.php?id=". $row[' id '] ."' title='View' data-toggle='tooltip'><span style='margin-left: 7px;' class='la la-file-o ks-icon'></span></a>"; echo "<a class='btn btn-warning mr-2 mt-2' href='updateLot.php?id=". $row['
id '] ."' title='Edit ' data-toggle='tooltip'><span style='margin-left: 7px;' class='la la-pencil ks-icon'></span></a>"; echo "
<a class='btn btn-danger mt-2' href='deleteLot.php?id=". $row[' id '] ."' title='Delete ' data-toggle='tooltip'><span style='margin-left: 7px;' class='la la-close ks-icon'></span></a>"; echo "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>";
// Free result set mysqli_free_result($result); } else{ echo "
<p class='lead'><em>No Lots were found.</em></p>"; } }
Here in the form I'm using: The user selects lot status - I want to change the color of the status based on what they chose.
<select class="form-control" value="<?php echo $lotstatus; ?>" id="lotstatus" name="lotstatus">
<option value="NA">N/A</option>
<option value="Executed">Executed</option>
<option value="Not Interested">Not Interested</option>
<option value="Hold">Hold</option>
<option value="Title Ordered">Title Ordered</option>
<option value="Vetting">Vetting</option>
<option value="Survey Ordered">Survey Ordered</option>
<option value="Lean Search Ordered">Lean Search Ordered</option>
<option value="Clear to Close">Clear to Close</option>
<option value="Closed">Closed</option>
</select>
I've tried styling the option value and also tried selecting the text() value of the field. Nothing is working... HELP!
First you need to add each row the status:
<tr class=\"Executed\">"; echo "
<tr class=\"Hold\">"; echo "
With JS you can add to the parent <table> the selected status:
$('select#lotstatus').on('change', function() {
$('table').attr('status', $(this).val());
});
Then, in your css you need to set the color that you want for each status:
table[status="Executed"] tr.Executed .statuscolor { color: red; }
table[status="Hold"] tr.Hold .statuscolor { color: green; }
table[status="Closed"] tr.Closed .statuscolor { color: yellow; }
Maybe you need to add an "id" to the table to avoid interferences with other tables.

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

JQuery preventDefault not working with .on click

I have a row of data, which when clicked, show information about the object.
But I also have a button on the row, which when clicked performs some jquery wizzardry.
Anyway, I can't seem to prevent the row click and just fire the button stuffs.
I've tried:
return false;
e.preventDefault();
e.stopPropagation();
This is the function.
$('#check_container').on('click', '.show_sub_orgs', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
I have all 3 in there at the moment, but that's just for example. Although I have tried all 3 in there, but I have also tried each one separately.
Heres the HTML
<div class="row" id="check_container">
<div id='table_holder' class="col-md-12" >
<table id="org_table" class="sortable table table-striped tablesorter">
<?php
if(empty($org_data2)) {
// if there is no data for the selected filter
echo "There are no organisations set up.";
} else {
echo "
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Sub Orgs</th>
<th>Locations</th>
<th>Users</th>
<th>Compliance</th>
<th>O/D Checks</th>
<th>O/D Training</th>
<th>Renewal</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
";
foreach ($org_data2 as $orgs) {
if(!$orgs->descendant) {
echo "<tr id='" . $orgs->org_id . "' class='edit_org_row clickable'>";
echo "<td>" . (($orgs->ancestor)?'<div id="' . $orgs->org_id . '" class="show_sub_orgs btn btn-primary btn-xs" data-toggle="tooltip" title="Show Sub-Orgs"><i class="fa fa-expand" aria-hidden="true"></i></div>':'') . "</td>";
echo "<td data-title='Name'>" . $orgs->org_name . "</td>";
echo "<td data-title='Sub Orgs' class='text-center'></td>";
echo "<td data-title='Locations' class='text-center'>" . $orgs->locations . "</td>";
echo "<td data-title='Users' class='text-center'>" . $orgs->users . "</td>";
echo "<td data-title='Compliance' class='text-center'></td>";
echo "<td data-title='O/D Checks' class='text-center'>" . $orgs->checks . "</td>";
echo "<td data-title='O/D Training' class='text-center'>" . $orgs->training . "</td>";
echo "<td data-title='Renewal'>" . date("d/m/Y", strtotime($orgs->renewal_date)) . "</td>";
echo "<td data-title='Actions'><div data-id='3' id='" . $orgs->org_id . "' class='btn admin_login btn-success btn-sm' data-toggle='tooltip' title='Login as customer'>Login</div><div data-id='2' id='" . $orgs->org_id . "' class='btn btn-danger btn-sm' data-toggle='tooltip' title='Disable customer'>Disable</div></td>";
echo "</tr>";
}
}
}
?>
</tbody>
</table>
</div>
</div>
What am I doing wrong?
When you delegate to a child element you need to use e.stopImmediatePropigation()
Jquery uses it's own event system and this will stop any execution on the elements delegated to from the parent. e.stopPropigation() will allow all events delegated from the same parent to fire
$('#check_container').on('click', '.show_sub_orgs', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
})

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