AJAX form refreshes page - javascript

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

Related

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.

JS sequential calling of function fails

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

Pass MYSQL row id to javascript variable

I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!

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.

ajax POST on form sumbit event not working properly

i have problem with ajax post with form submit event. i have table generated by opentable.php
here code for opentable.php
<?php
session_start();
require("dbc.php");
$memberid = $_SESSION['memberid'];
$sql = "SELECT * FROM `open` WHERE `memberid`='$memberid'";
$mydata = mysql_query($sql);
echo "<table><tr><th>Time</th><th>Type</th><th>Size</th><th>Price</th><th>Profit</th><th></th><th></th></tr>";
while($record = mysql_fetch_array($mydata)){
echo "<form action = assets/close.php id=closeform>";
echo "<tr>";
echo "<td>" . $record['opendate'] . "</td>";
echo "<td>" . $record['type'] . "</td>";
echo "<td>" . $record['size'] . "</td>";
echo "<td>" . $record['openprice'] . "</td>";
echo "<td>" . $record['profit'] . "</td>";
echo "<td>"."<input type=hidden name=openid value=".$record['openid']." </td>";
echo "<td>" . "<input type=submit name=close value=close". " </td>";
//echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
and ajax javasript for submit event trade.js
$(document).ready(function() {
$('#closeform').submit(function( event ) {
event.preventDefault();
var $form = $( this ),
price = $('#price').val(),
id = $form.find( "input[name='openid']" ).val(),
url = $form.attr( "action" );
var posting = $.post( url, { openid: id, closeprice: price } );
var r=confirm("Are you sure?");
if(r =true){
posting.done(function( data ) {
alert(data);
});
}
else
{
alert("Transaction canceled")
}
});
}
i tested it, and it runs like normal php form. and error there is no $_POST data passed.
please give me recomendation for this kind of event thanks.
closeform is a dynamically added form, try using .on():
$(document).on('submit', '#closeform', function ( event ) {

Categories