JS sequential calling of function fails - javascript

I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.

The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working

Related

PHP wrong database edit

I'm setting up a dynamic webpage that will be used as a time stamp for employes. After you log in, you will write down when you started work, how long the break was, when you finished and so on..
Problem is that every time I wanna change something on the webpage, for example I want to change my break time, it won't change and shows me the user_id instead.
I'm still a beginner when it comes to PHP and don't know where the problem is..here are some code snippets
<div class="header">
<ul>
<li>
<p class="text">HourBook</p>
</li>
</ul>
</div>
<table class="table table-striped table-bordered">
<tr>
<th class="luecke1">Name</th>
<th class="luecke2">Start Time</th>
<th class="luecke3">Pause</th>
<th class="luecke4">End Time</th>
<th class="luecke5">Comments</th>
<th class="luecke6">Duration</th>
</tr>
<?php
$connect = new mysqli('localhost', 'root', '', 'hourbook');
$result = $connect->query("SELECT * FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>";
echo "<td class='luecke1'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['user_id'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\"})'></input></td>";
echo "<td class='luecke2'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['start_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"start_time\"})'></input></td>";
echo "<td class='luecke3'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['pause_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"pause_time\"})'></input></td>";
echo "<td class='luecke4'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['end_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"end_time\"})'></input></td>";
echo "<td class='luecke5'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['comments'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"comments\"})'></input></td>";
echo "<td class='luecke6'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['total_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"total_time\"})'></input></td>";
}
} else {
echo "No results!";
}
?>
<script>
var oldValue;
function pruefung(params) {
var newValue = document.getElementById('editor' + params.currentid).value; //editor id verknüpfung falsch?
if (oldValue == newValue) {
console.log("no changes");
} else {
console.log("changes");
$.ajax({
url: "update.php",
type: "POST",
data: {
value: newValue,
id: params.currentid,
fieldname: params.currentfieldname
},
success: function(data) {
alert("Saved successfully!");
document.location.reload(true);
},
error: function(data) {
alert("error: " + data);
}
})
}
}
</script>
</table>
In your AJAX call you have : var newValue = document.getElementById('editor' + params.currentid).value;
In your table, for each row you have : id='editor" . $id . "'. This is a duplicate of ids.
When doing var newValue = document.getElementById('editor' + params.currentid).value; You are getting the first element that has this id, that's why newValue is always the id (the first row holding the id value)
I suggest you to remove that var newValue = ... but instead insert the value in the object you pass as parameter of pruefung(), such as onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['user_id'] . "\"}) for the id row, onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['start_time'] . "\"}) for the start time row, and so on...
And then, in your AJAX call, replace var newValue = document.getElementById(...) by var newValue = params.value

Choose an amount of certain item from the database to save into a variable

I'm trying to make a way to take a certain quantity of a product from all displayed from the database, for example I want to take 3 out of 5 possible ones with me but I have no idea what I need to add to make it so, right now it displays the data like this:
foreach ($order->get_items() as $item ){
$unitprice = $item->get_total() / $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() . "|" . $item->get_quantity() . "|" . $item->get_total() ."'>";
echo '<p>';
echo __('Product name: ' ) . $item->get_name() . '<br>';
if($item->get_quantity() > 1) {
echo "Amount: " . "<input type='number' name='numberqty' value='" . $item->get_quantity() . "'max='" .$item->get_quantity() . "' min='0' > " . "<br/>";
}
else {
echo __('Amount: ' ) . $item->get_quantity() . '<br>';
}
echo __('Product individual price: ') . $unitprice . '€' . '<br/>';
echo __('Product total: ' ) . wc_price($item->get_total()) . '</p>' . '<br/>';
}
echo '<p>'. __('Order total: ') . $order->get_total() . '</p>';
I'm not very good at making questions so ask if something is unclear.

passing variable from while loop when user press link (php)

i am searching for a way to pass variable ($result[1]) to a session variable from while loop within a link. will be glad for some help
while ($result = mysqli_fetch_array($dataset,MYSQLI_NUM)){
echo "<tr>";
echo " <td >", "<a href='Rate_Supplier.php'>" . $result[1] ."
</a>","</td>" ;
echo " <td >" . $result[0] . "</td>" ;
echo " <td >" . $result[2] . "</td>" ;
echo "</tr>\n";
}

AJAX form refreshes page

Have been searching around for a while and can't find a proper answer to this problem. I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again.
On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem.
Here is the related code from the PHP file:
if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }
(other code)
$(document).ready(function() {
$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'FBook.php',
data: $(this).serialize(),
success: function() { alert('form submitted'); },
});
return false;
});
$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });
(other code)
});
(other code)
$AssetCounter = 1;
$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))
{
$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}
if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }
$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }
echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";
$AssetCounter++;
}
Your JavaScript:
$("#AssetUpdateForm")
… is working on a form with id="AssetUpdateForm".
Your PHP says:
id='AssetUpdateForm[" . $AssetCounter . "]'
which in HTML terms becomes:
id='AssetUpdateForm[something]'
Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element.
You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript.
NB: Your HTML is invalid. The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. Use a validator and write valid HTML too.
Had nothing to do with the HTML or PHP. Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' property. I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine.
$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'FBook.php',
data: $(this.form).serialize(),
success: function(html) {
console.log('Successfully submitted AJAX!');
$("#TableAssets").replaceWith($('#TableAssets', $(html)));
}
});
});

How to pass a MySQL data from PHP to Javascript through a function

I'm making a program that shows several descriptions taken from a database (MySQL):
echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
. " onclick=cambiarBoton(" . $i . ", \"" . $row["descripcion"] . "\") />";
echo "<div class=\"entrada-descripcion\" id=\"Descripcion" . $i . "\"> </div>";
where $row["descripcion"] is the access to the description and $i is an identifier because i'm using loops. That code generates a button that i must press to show the description. The javascript function "cambiarBoton" is the one that do that changes:
function cambiarBoton(i, d){
if (document.getElementById("Boton"+i).value == "Mostrar Descripcion"){
document.getElementById("Boton"+i).value = "Ocultar Descripcion";
document.getElementById("Descripcion"+i).innerHTML = d;
}else if(document.getElementById("Boton"+i).value == "Ocultar Descripcion"){
document.getElementById("Boton"+i).value = "Mostrar Descripcion";
document.getElementById("Descripcion"+i).innerHTML = "";
}
}
Ok, but there is a problem in the program and this is that i can't pass the description to the function in javascript and this doesn't works. How can i do this?
(I must do this without using AJAX)
I answer to the question I think you're asking is:
<?php echo "<script>var data = ".$row["description"].";</script>"; ?>
The problem was in the call of the function "cambiarBoton" in the code PHP,
it should have been this:
echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
. " onclick=\"cambiarBoton(" . $i . ", '" . $row["descripcion"] . "')\" />";
And then it works.

Categories