I have a PHP calendar application that presents a schedule in table form. Each cell is selectable and has the following Jquery popup code behind it:
document.getElementsByTagName('body')[0].appendChild(f);
if (roleID > 2)
{
window.open("","popUpForm","height=550,width=1050,toolbar=0,menubar=0,location=100,status=no,scrollbars=1,resizable=1,right=300,top=100");
$('.jobTime').submit();
}
That works fine and presents a form called newJobForm.php in the popup window. The user enters selected times...and submits. If there is a conflict with the attempted schedule the window popup is closed and the form is reopened with with conflict information:
else
{
$userSTime = new DateTime($params[0]);
$userSTime = date_format($userSTime,'m/d/Y h:i a');
$userETime = new DateTime($params[1]);
$userETime = date_format($userETime,'m/d/Y h:i a');
$_SESSION['jbNum'] = $params[2];
$_SESSION['asset'] = $params[4];
$_SESSION['userSTime'] = $userSTime;
$_SESSION['userETime'] = $userETime;
$_SESSION['userDesc'] = trim($params[3]);
$_SESSION['conJbNum'] = $msg['JobNum'];
$_SESSION['conSTime'] = date_format($msg['StartTime'], 'm/d/Y h:i a');
$_SESSION['conETime'] = date_format($msg['EndTime'], 'm/d/Y h:i a');
$_SESSION['dueDate'] = $params[5];
$_SESSION['comment'] = $params[6];
$_SESSION['destination'] = $params[7];
$_SESSION['jStat'] = $params[8];
$_SESSION['ujob'] = $params[9];
if ($_SESSION['recurring'] == 'n')
{
echo '<script>window.open("../forms/newJobForm.php","popUpForm","height=550,width=900,status=yes, scrollbars=1, toolbar=no,menubar=no,location=no");</script>';
windowClose();
exit;
}
This part works fine if the user makes the right corrections. However, if the user makes another scheduling error the form will close and redisplay information. At this point the close function quits working and the original parent page doesn't refresh. The parent page not refreshing I kind of understand, but the close function is simply that 'close'.
function windowClose()
{
echo "<script>window.close()</script>";
}
what is going wrong? I can't really post the whole code because there is about 1000 lines of code, give or take... How can I get this to work properly?
Thanks to #CBroe I was able to solve this particular problem with the following modifications to my application. In my file where I check the user input for any conflicts with existing entries I changed:
if ($_SESSION['recurring'] == 'n')
{
echo '<script>window.open("../forms/newJobForm.php","popUpForm","height=550,width=900,status=yes, scrollbars=1, toolbar=no,menubar=no,location=no");</script>';
windowClose();
exit;
}
to:
if ($_SESSION['recurring'] == 'n')
{
echo "<meta http-equiv='refresh' content='0;URL=../forms/newJobForm.php' target = '_SELF'/>";
exit;
}
Which simply refreshes the original form with the new conflict (if there is a conflict) information, or allows the user to submit or cancel the attempted action regardless of how many times they try. And to the form its self I added the following javascript make sure the user's actions refresh the parent page:
window.onunload = refreshParent;
function refreshParent()
{
window.opener.location.href = window.opener.location.href;
}
And the function that creates the initial popup was slightly modified like this:
document.getElementsByTagName('body')[0].appendChild(f);
if (roleID > 2)
{
popUpForm = window.open("","popUpForm","height=550,width=1050,toolbar=0,menubar=0,location=100,status=no,scrollbars=1,resizable=1,right=300,top=100");
$('.jobTime').submit();
}
I hope others will find this useful.
Related
I've created this code so that the user will not redirect onto the next page again. I set the maximum value on votenow button to 1 and once the user click the button again the value on the votenow button will not be added anymore since its maximum is 1. Everything works fine except that the user can still access the nextpage though the maximum value on the button was reached. Here's the code.
<?php
$errors = array();
$db = mysqli_connect("localhost","root","","registration");
if(isset($_POST['votenow']))
{
$votenow ="0";
$votenow1="1";
if($votenow != $votenow1){
$votenow = "update users set votenow = votenow + 1 WHERE votenow=0 LIMIT 1 ";
$run_vote = mysqli_query($db,$votenow);
echo '<script type="text/javascript">alert("hello!");</script>';
header ("Refresh:2; url=renewsys3.php");
}
else{
echo '<script type="text/javascript">alert("oh not again!");</script>';
header ("Refresh:2; url=renewsys2re.php");
}
}
?>
Can you guys help me or is there any other way so that the user will not enter the next page again? Btw, this is a voting system
The best way to use session:
$_SESSION['votenow'] = 0;
if (isset($_SESSION['votenow'])) {
if (!$_SESSION['votenow']) {
//do something
} else { // means $_SESSION['votenow'] == 1
// do something else
}
}
Redirect the URL to a different page (maybe homepage or any page) If the maximum vote is reached.
Let that code run before any other code so that the page won't load of the condition is true. It'll redirect immediately.
I'm working on membership module. And, found that data saving twice for membership_record table.
What I'm doing is: After calculating total amount, tax etc. I'm saving it and redirecting it to payment gateway URL. From there, response coming to my controller function checkout(), where data is entering twice.
public function actionSubscription(){
..
..
if($modelMemberships->load(Yii::$app->request->post())){
/*
* Ajax Validation Code
*/
$validMembership = $modelMemberships->validate(['addTeamMember','is_free_trial']);
if($validMembership){
$postMemberships = Yii::$app->request->post('Membership');
.
.
if($modelMemberships->save()){
$redirectURL = Yii::$app->params['_URL'].'memberships/checkout?id='.$modelMemberships->getId();
return $this->redirect($redirectURL); //This is redirecting to checkout function.
}
}
}
}
public function actionCheckout($id){
$payment_status = "Y";
if($payment_status == "Y"){
foreach($modelUsers as $modelUser){
$modelMembershipUsers = new MembershipUsers();
$modelMembershipUsers->membership_id = $modelMemberships->getId();
$modelMembershipUsers->save();
}
//Update UC Settings
if($modelUCSettings = UCSettings::findOne($UCSettingsId)){
$modelUCSettings->updated_at = date("Y-m-d h:i:s");
$modelUCSettings->save(false);
}
return $this->redirect(['#web/memberships/receipt?id='.$id]);
}
}
And, there is no code duplication. So, from no where this code will get executed until it is redirected from subscription() function.
I don't know why data is saving twice only in membership_records table.
I Checked data is saved twice to the database. But, the answer provided doesn't resolved my problem.
Adding to it: In google chrome, there is no duplicate records. But, by using mozilla firefox, data is saving twice.
Any help/suggestions is appreciated.
i'm quite a beginner with PHP and i tried to make something to get xp when cliking the button. You just need to click and it gives xp, then it refresh the page to refresh the player's stat on screen.
<form method="post">
<p><input type="submit" value="Kill the mob" name="add20xp" /></p>
</form>
<?php
if (isset($_POST['add20xp']))
{
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
?>
The problem is that i want to prevent the user from smashing the button to prevent bugs and things like that... I tried to put sleep(1) but i can just keep spamming, wait the seconds and it works so it's not very useful.
Thanks for the help !
Save the last time the update was done in session state. Then, only allow the button to be pressed after (last time + 2 seconds) (Two seconds was chosen since that was the suggested interval in your original question).
if (isset($_POST['add20xp'])) {
if (!isset($_SESSION['last_post'])) {
$_SESSION['last_post'] = 0;
}
$currtime = time();
if ($currtime > ($_SESSION['last_post'] + 2)) {
$_SESSION['last_post'] = $currtime;
// ... process the post.
$add20xp =("UPDATE users SET exp = (exp + 20)"); // fix this line
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
}
As #Martin noted above in his comment, you want to do the update only for the user who pressed the button, which is the meaning of the comment "fix this line."
If you want to disable the button for 3 seconds after the form is submitted you can use this:
if(sessionStogare.getItem('submitted') === true){
document.querySelector('input[type="submit"]').disabled = true;
setTimeout(function(){
document.querySelector('input[type="submit"]').disabled = false;
sessionStorage.removeItem("submitted");
}, 3000);
}
document.querySelector("body").onclick = function() {
sessionStorage.setItem("submitted", true);
};
We will note the submission in the sessionStorage and check, if the form has been submitted every time we load the page. Then, we will disable the button and enable it after 3 seconds.
Change your php page to this:
// the beginning of the page:
<?php
// start a SESSION
session_start();
// setup a $_SESSION variable
if (!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
//
// now put the $_POST part
if (isset($_POST['add20xp'])) {
// check the time
$now = time();
if ($now - $_SESSION["timestamp"] > 2) {
// more than 2 seconds have passed since last $_POST
// update the time
$_SESSION["timestamp"] = time();
//
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
//
echo '<meta http-equiv="refresh" content="0.1" />';
exit;
} else {
// nothing, just let the page load like it is.
}
}
?>
Notice some important changes:
the use of $_SESSION vars -> these vars are stored and can be
retrieved at every page load -> you can use them to store the last
time an action took place
the $_POST part should be at the beginning
of the page -> otherwise after you send a form, you load the page ->
check the post -> then reload... it's not efficient
if you put the $_POST part at the beginning, you actually don't need the page reload with the meta tag -> because the data are already
updated
I'm trying to make you redirect to the successful page after succesfully registering but whenever I click the register button I get redirected instantly even if all the input's are empty
if(isset($_POST["registration"])){
if(!empty($_POST["gender"])
and !empty($_POST["username"])
and !strlen($_POST["username"]) < 3
and !empty($_POST["email"])
and !email($_POST["email"])
and !empty($_POST["emailver"])
and !verification($_POST["email"],$_POST["emailver"])
and !empty($_POST["password"])
and !strlen($_POST["password"]) < 8
and strlen($_POST["password"]) < 25
and checkUppercase($_POST["password"])
and checkLowercase($_POST["password"])
and checkNumber($_POST["password"])
and !empty($_POST["passwordver"])
and !verification($_POST["password"],$_POST["passwordver"])){
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_POST["password"]) === TRUE){
$url = 'succesfull.html';
header($url);
}
}
}
The function for addgamers
function addgamer($db,$gender,$username,$email,$password){
$sql = "INSERT INTO gamers (`gender`, `username`, `email`, `password`) VALUES('$gender','$username','$email','$password')";
$db -> exec($sql);
if ($db->query($sql) === TRUE) {
$GamerId = $db -> lastInsertId();
$_SESSION['GamerId'] = $GamerId;
return true;
} else {
return false;
}
}
I found some answers here but all of them do the same and I have no solution for this.
GOTO($url);
Or
header('location: $url');
Or
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_SESSION["password"]) === FALSE ){
die();
}else{
$url = 'successful.php';
header($url);
}
Also tried with jQuery
echo "<script>window.location = '$url'</script>";
On every single click on the registration submit button you get redirected to the successful page but that should not happen until everything is filled in correctly as shown from the above code.
As you can also see I'd like to fix this problem trying with php only first.
Validate before submitting the form would be better at first.
As #Nicolas D mentioned you should also know that the form action is the page you direct to no matter what.
You can however set this to the current page by using action="" or action="<?php echo $_SERVER['PHP_SELF']; ?>"
This last could come with exploits, you can use "htmlentities($_SERVER['PHP_SELF'])" instead. Read about this here.
You have a missunderstanding PHP problem.
If your form use a submit form, it will post automatically to the php page targeted.
If you don't want to post to a new page and still verify your data, then you must use ajax in jquery : http://api.jquery.com/jquery.post/ . With that you ll catch your data without unexpected redirection.
Once all your form is validated by your php code during ajax call, you can redirect in jquery on the callback function.
Hope this will help, I ve been through this step and I remember it was painful
I've been trying to get user input from a Javascript prompt into a PHP function and have run into a lot a walls doing so. I am at a loss trying jQuery's $.post method- as the PHP simply does not want to execute, not sure why.
Anyways, here is a gist of what I am doing at the moment:
1 A project and its data are loaded from a database- this info is displayed in a table.
2 All data in the table is editable via Javascript prompt(), the code I am using for this is below:
<div id="lvl3"><?php echo $fetchdata['name']; ?></div>
The above work as such: lvl3 is a tag for font styling; blank href to make it act as a link; popupprompt is the prompt function I made, it takes one argument, the 'type' or what is being edited (1 for project name, 2 for project description, ect); return false so the page doesn't reload; php echo to display project data in the table.
3 Once the user clicks the object above- it executes a javascript function called popupprompt taking an argument of 'type', or what project info is being changed. the code for this function is below:
function popupprompt(type) {
switch(type)
{
case 1:
var name = prompt("Project Name:", "");
if (name != null && name != "")
{
//Change Project Name
var getname = name;
var gettype = type;
$.post("edit.php", { type: gettype, name: getname });
} else if (name == "") {
senderror("Please enter a valid Project Name");
} else {
//Prompt canceled
sendnotification('Canceled my ass!');
}
break;
case 2:
//Description?
case 3:
//Version?
case 4:
//Release?
default:
alert("There was an error processing your request.");
break;
} }
Th issue I am having in this function is that nothing in edit.php is executed- and i haven't the slightest clue why. Also, i've had to change the brackets around so it shows properly in the code box- so don't mind those.
4 Anyways, now user input is posted to edit.php- which doesn't work, but i'll post it anyways:
<?php
$type = $_POST['type'];
$name = $_POST['name'];
switch($type) {
case 1:
dbconnect();
$urlext = geturlext();
$authenticated = isauthenticated();
if ($authenticated == false)
{
echo("<script>senderror('Access denied');</script>");
} else {
//Escape and trim input
$input = trim($input);
$input = mysql_real_escape_string($input);
$update = "UPDATE 'projects' SET 'name' = '$input' WHERE 'name' = '$urlext'";
$updatequery = mysql_query($update) or die(mysql_error());
echo("<script>sendnotification('Project Name updated');</script>");
}
break;
default:
break;
}
?>
Again had to move some brackets around. But anyways- this function is supposed to update the data in the database- however, it instead does nothing. I've placed alerts in the beginning and they are never called.
Anyways, long story short- if you know what i'm doing wrong please enlighten me, also, if there is a better way to do this- please let me know!
I appreciate all help,
Thanks
Figured it out after a good week of setting it aside. Took a long look at it in firebug, rooted out a typo that was causing most of my issues and also a MySQL syntax error.
I don't know why, but my custom error reporting system does not work when called from a file in this manner. It might be another thing i'm overlooking but firebug sure helped.
Thanks to those who tried to help <3