Prevent Javascript form use back data on Back click - php

I create table using ajax. When i click on button it will read the row and create a form using ajax.
Everything is fine here. But when i click back button on browser, the data is somehow posted/display back as FORM. How to delete/prevent this when click on back.
Thing i have read:
1) Clear input for form. But where is reading input because form is created using function submitRowAsForm when button is clicked
2) Disable autocomplete. But this doesnt seem relevant and not work.
$(document).ready(function update(){
$.ajax({
url: 'getSchedule.php',
success: function(data,status)
{
createTableByForLoop(data);
},
async: true,
dataType: 'json'
}).then(function() { // on completion, restart
setTimeout(update, 30000); // function refers to itself
});;
});
function createTableByForLoop(data)
{
var table = "\
<div class='table-scrollable'>\
<table class=\"table table-responsive\">\
<thead >\
<tr>\
<th class=\"d-none\">ID</th>\
<th class=d-none>SHOWSCHEDULE_ID ID</th>\
<th>TITLE</th>\
<th>TIME</th>\
<th>ACTION</th>\
</tr>\
</thead>\
<tbody>"
for(var i=0; i<data.length;i++)
{
table += "<tr id=\""+i+"\">";
table += "<td class=d-none><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_ID value=\""+data[i]['SHOWSCHEDULE_ID']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_SHOWTITLE value=\""+data[i]['SHOWSCHEDULE_SHOWTITLE']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWBEGINTIME value=\""+data[i]['SHOWBEGINTIME']+"\" readonly> - <input type=text class=\"form-control transparent-input\" name=\""+data[i]['SHOWENDTIME']+"\" value=\""+data[i]['SHOWENDTIME']+"\" readonly></td>";
table += "<td><button onclick=submitRowAsForm("+i+") id=btnRoom class=\"btn btn-outline-success\" >Room</button>\
<button onclick=submitRowAsForm("+i+") id=btnBook class=\"btn btn-outline-warning\" >Book</button></td>";
table += "</tr>";
}
table +="</tbody></table></div>";
$('#idShowSchedule').html(table);
}
function submitRowAsForm(id) {
form=document.createElement('form');
form.method='POST';
form.action='OrderTicket.php';
$("#"+id).children().each(function() {
$(this).children().each(function(){
$(this).clone().appendTo(form);
});
});
document.body.appendChild(form);
form.submit();
}

To protect against the back button I would set a dirty flag on your page. That way when it's set you know you have done this before. So
Check to see if your dirty flag is set
If not set your dirty flag
Load data because this is a fresh loading of the page.
Make sure that you do this after the DOM Content has Loaded otherwise this will fail in some browsers.
Here is an example of how I didn't this in one of my old projects
document.addEventListener("DOMContentLoaded", function (event) {
var dirty = 0;
var dirtyEl = document.getElementById('page_is_dirty')
if (!dirty && dirtyEl && (dirtyEl.value != "0" && dirtyEl.value != "")) {
dirty = 1;
}
else if (dirtyEl) {
dirtyEl.value = '1';
}
var el = document.getElementById('ClickApp');
if (el && !dirty)
el.innerHTML = "<div id='ClickApp' ng-view='' click-main><br /><br /><center><h2>Loading Calendar</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
else {
var dirtyMEl = document.getElementById('page_is_dirty_message');
var dirtyMSG = dirtyMEl ? dirtyMEl.value : "You arrived here by hitting the back button. Please start over.";
el.innerHTML = "<div><br /><br /><center><h2>" + dirtyMSG + "</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
}
if (!dirty) {
//Do your data loading. Page transformaions, whatever
...
}});

Related

Running PHP function when PHP echoed HTML Button is clicked

I am Working on the project with my school but I have no idea how to call a PHP function when HTML button is clicked
<?php
function sqlUpdateTheScore($idMinusOneString){
$idminusOneVal=(int)$idMinusOneVal;
$MsgQuery=mysqli_query($conn,"UPDATE Point SET Point=".returnCurrentPoint($idMinusOneVal)."WHERE id=".($idMinusOneVal+1).";");
}
for($i=0;$i<$tot;$i++){
print "<tr>" ;
print "<td align='center'>" .$tot_result[$i][0]."</td>";
print "<td align='center'>" .$tot_result[$i][1]."</td>";
print "<td align='center'>" .$tot_result[$i][2]."</td>";
print "<td align='center'><button id='dec_".$i."' onclick='decreaseByOne(".$i.");'>-1</button><div id='pointOfStudent".$i."'>" .$tot_result[$i][3]."</div><button id='inc_".$i."' onclick='increaseByOne($i);'>+1</button></td>";
print "<td align='center'><button onclick='sqlUpdateTheScore($i);'>SAVE</button></td>";
print "</tr>" ;
}
?>
it's the sqlUpdateTheScore(); function at the top
You can't directly call php functions from html. (I also find this annoying)
There are two workarounds you can use. The easiest is a form:
<form action="thePage.php" method="POST">
<input type="text" name="newValue" id="newValue" hidden />
<button onclick="changeValue()">Change Value</button>
<input type="submit" value="SAVE" name="submit" />
</form>
JavaScript:
function changeValue() {
document.getElementById("newValue").innerText = "Some new value";
}
PHP:
if (isset($_POST["submit"])) {
$newValue = $_POST["newValue"]; // You can then run functions off this value
}
The other way is to use AJAX. Here is a good turorial.
Try this
PHP:
Change your SAVE button part to
<button class="save_button" value=$i>SAVE</button>
Add
if (isset($_POST['idMinusOneString'])) {
sqlUpdateTheScore($_POST['idMinusOneString']);
}
JS:
add AJAX (with jQuery)
$('.save_button').click(function() {
$.ajax({
type: "POST",
url: "this.php",
data: { idMinusOneString: $(this).val() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});

why is jquery not passing a post value

I have a page with two forms on it. This shouldn't be a problem, but it is not working. My jquery looks like this:
$(document).ready(function()
{
$("table.jobs tbody tr td#ejob").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
$('#jobid').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#jobUpdate').submit();
});
var now = new Date();
var month = now.getMonth()+1;
var day = now.getDate();
var year = now.getFullYear();
if (month<10){month='0'+month}
if (day<10){day='0'+day}
var now = month +"/"+ day + "/" + year;
var calendarBox = $('#calDate');
//$('#calDate').val(calendarBox.datetimepicker('getDate'));
var thisone = $('#calDate').val(calendarBox.datetimepicker('getDate'));
calendarBox.datepicker(
{
minDate:('setDate', '' , new Date()),
defalt:calendarBox.val(now),
onSelect: function (selectedDateTime)
{
$('#calDate').val(calendarBox.datetimepicker('getDate'));
alert("Sendeing " + $('#calDate').val(calendarBox.datetimepicker('getDate')));
$('#calendarForm').submit();
}
});
}
);
and my forms look like this:
echo "<form id='calendarForm' action='view_rev8.php' method='POST'>";
echo "<table border='0' width='100%'class='calendarTable'>";
echo "<tr><td align='left'>Click on a job number to update or change job information</td>";
echo "<td align='right'></td>";
echo '<td align="right">Calendar: <input type="text" id="calDate" size="15" name"calDate"/></td></tr>';
echo "</table>";
echo "</form>";
//creates the form to post jobid for updateJobForm.php
echo'<form id="jobUpdate" action="../forms/updateJobForm.php" method="post">';
echo'<input type="hidden" name="jobid" id="jobid">';
echo '</form>';
The first function handles when a user clicks on a table item and submits the post value without a problem. The datepicker works and the form gets submitted, but i get the following error: Undefined index: calDate from the following page:
$pickedDate = $_POST['calDate'];
include_once("../php/job_class.php");
echo $pickedDate;
$obj=new jobs();
echo "<div style='border:solid 1px '>";
foreach ($obj as $val)
{
echo "<pre>";
echo print_r($obj);
//echo $obj->jobInfo();
echo "</pre>";
echo "</div>";
}
Why is this not working? It is a simple post from a well defined form, and as far as I can see all fields are named consistently and accurately.
You have invalid HTML in the input tag. (It's missing an = sign.)
<input type="text" id="calDate" size="15" name"calDate"/>
should be:
<input type="text" id="calDate" size="15" name="calDate"/>
So your JS is setting the value since you're using the ID, but the name is what is used for posting a form, which is why it is empty.

jQuery ajax script wont work with n number of forms from PHP

I have a little problem with my AJAX jQuery script and n number of forms...To be more precise, PHP script generate N number of forms (form include one textarea and one button), and in head tag I included jquery script. Problem is that jquery work only for first form and not with others (second, third...). I needed to work with all forms...This is the code:
<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
And this is PHP code
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>
</div>";
}
What is problem???
On your PHP side you should change with something similar to this to ensure that all the html elements has a unique id.
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>
</div>";
}
and change the Javascript with something similar to this to reflect the changes made on the php side
<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
For every form you're creating you're using the same ID.
IDs must be unique and only appear once on the page.
You should use a class instead as suggested in the comments.
So more like this:
<?php for ($i = 0; $i < $num; $i++): ?>
<div>
<textarea class="comment"></textarea>
<input type="hidden" class="id" value="<?php echo $id; ?>">
<input type="button" class="submitForm" value="Add Comment">
</div>
<?php endfor; ?>
I'm not sure where your $id variable comes from.
Your JavaScript will need to be updated as well to work with this, I'd do something like this (elaborated so you can see what's going on):
$('.submitForm').click(function(e) {
e.preventDefault(); // stops the default form action (if there is one)
var $submitButton = $(this);
var $div = $submitButton.parent(); // gets the div container
var id = $div.find('.id').val();
var text = $div.find('.comment').val();
// now do your ajax
});

JQuery submit textarea on return key press using AJAX post

I have comment boxes beneath posts on my website, and I'd like people to be able to submit a comment by simply pressing the return key. The comment is also inserted via ajax.
My code as it stands is:
For the AJAX post and capturing the enter key:
$('textarea#scat').bind('keypress', function(e) {
if(e.keyCode==13){
var myClass = $(this).attr("class");
var comment = $("textarea." + myClass).val();
if (comment == "") {
return false;
}
if (!$.trim($("textarea." + myClass).val())) {
return false;
}
var cid = $("input.c_" + myClass).val();
var itemid = $("input.i_" + myClass).val();
var type = $("input.t_" + myClass).val();
var top = $("input.l_" + myClass).val();
var dataString = 'comment='+ comment + '&cid=' + cid + '&itemid=' + itemid + '&type=' + type;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "addcomment.php",
data: dataString,
success: function() {
$('#c').load('ajax/querylc.php?oid=' + myClass);
$("textarea." + myClass).val('');
}
});
return false;
};
});
And my comment box code:
<div id='statuscomadd' class="<?php echo $sid; ?>" style='text-align:center; padding-top:2px; margin-left:12.5px; border-left:1px #a3a3a3 solid; border-right:1px #a3a3a3 solid; border-bottom:1px #a3a3a3 solid; height:40px; width:420px; vertical-align:middle;'>
<img id="scati<?php echo $sid; ?>" src='<?php if ($dp == null) { echo 'img/unknown_user.jpg'; } else { echo 'pf/' . $uid . '/' . $dp; } ?>' style='height:36.5px; margin-right:5px; margin-bottom:6px;'>
<form action='addcomment.php' method='post' id='ac' style='display:inline; border:0px; margin: 0 0 0 0; padding: 0 0 0 0;'>
<textarea id='scat' style='outline: none; height:30px; width:315px; font-family:Arial; border:0px; resize:none; margin-bottom:5px; border:1px solid #C9C9C9; display:inline;' name='comment' class='<?php echo $sid; ?>'></textarea>
<input type='hidden' class="t_<?php echo $sid; ?>" name='type' value='status' />
<input type='hidden' class="i_<?php echo $sid; ?>" name='itemid' value='<?php echo $sid; ?>'/>
<input type='hidden' class="c_<?php echo $sid; ?>" name='cid' value='<?php echo $uid ?>' />
</form>
</div>
The post works if I use a form submit button, but not if I use the return key, all that happens currently is that it adds a new line, which I only want to happen on shift+enter.
Any help would be much appreciated!
Form the Docs on keypress http://api.jquery.com/keypress/:
Note that keydown and keyup provide a code indicating which key is
pressed, while keypress indicates which character was entered. For
example, a lowercase "a" will be reported as 65 by keydown and keyup,
but as 97 by keypress. An uppercase "A" is reported as 65 by all
events. Because of this distinction, when catching special keystrokes
such as arrow keys, .keydown() or .keyup() is a better choice.
So you actually want to use keydown with your function instead: http://api.jquery.com/keydown/
Instead of 'keypress' use the following.
$('textarea#scat').bind('**keydown**', function(e) {
if(e.keyCode==13){
Might have to do with the class attribute of your textarea.
Is the PHP variable $sid a number?
If so, try adding a non-numeric prefix like
class='classname_<?php echo $sid; ?>'

Javascript select all button in php

Hi All First of all I don't know Javascript, I got this script from the internet but can't get it to work. If someone can please be so kind and assist me. I'm trying to create a "check all" & "uncheck all" button on my form for my checkboxes, if I click the button it does not select anything. Where am I going wrong?
<?php
session_start();
?>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!--
<!-- Begin
function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}
function UnCheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
// End -->
</script>
</head>
And then the form:
$sql0 = "SELECT * FROM .....
$result0 = mysql_query($sql0);
echo "<form name='myform' action='...' method='post'>";
while($row0 = mysql_fetch_assoc($result0)) {
$test_id=$row0['id'];
$test_name=$row0['test_name'];
echo " <table width=600px>";
echo " <tr>";
echo " <td width=30px><input name='question[$test_id][]' type='checkbox' value='1' /></td>";
echo " <td width=580px align=left>$test_name</td>";
echo " </tr>";
echo " </table>";
}
echo "</P>";
echo "<input type='button' name='Check_All' value='Check All' onClick='CheckAll(document.myform.check_list)'>";
echo "<input type='button' name='Un_CheckAll' value='Uncheck All' onClick='UnCheckAll(document.myform.check_list)'>";
echo "</form>";
if you don't know javascript, i'd strongly recommend you investigate jquery - a library which eliminates cross browser issues and makes a huge amount of javascript far easier.
simply include this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
and your code
<input type='button' name='Check_All' value='Check All' onClick='$(":checkbox").attr("checked",true);'>
untested, but should be okay.
I'd highly recommend using jQuery, it allows you to focus on the logic and not worry about cross browser issues you might run into.
<script src='http://code.jquery.com/jquery-1.6.3.min.js' type='text/javascript'></script>
<script>
$(document).ready(function () {
//check all
$('input[name="Check_All"]').click(function () {
//for all checkboxes where the name begins with "question", check them
$('input[name^="question"]').attr('checked', true);
});
//uncheck all
$('input[name="Un_CheckAll"]').click(function () {
//for all checkboxes where the name begins with "question", uncheck them
$('input[name^="question"]').attr('checked', false);
});
});
</script>
Here's the breakdown...
Select all buttons on the page where the name attribute is set to Check_all
$('input[name="Check_All"]')
When the found item(s) are clicked, execute the code in the function that is passed
$('input[name="Check_All"]').click(function () {
//javascript code here
});
for all checkboxes where the name begins with "question", check them
$('input[name^="question"]').attr('checked', true);
Change this:
<td width=30px><input name='question[$test_id][]' type='checkbox' value='1' /></td>";
to this:
<td width=30px><input name='check_list[]' type='checkbox' value='1' /></td>";

Categories