Submit form one time after page load via Jquery - javascript

How to submit the cart request-quote form after page load?
Below code is worked fine -
<?php if(!isset($_GET['updated'])) { ?>
<script>
jQuery(document).ready(function($) {
jQuery("#yith-ywraq-form").submit();
});
</script>
<?php } ?>
But avoid submitting forms, again and again, I reload to this action
site.com/request-quote/?updated=data
But if someone refreshes the same page site.com/request-quote/?updated=data
then I have no option to submit the form again on page load.
do you have a solution for this problem?
My requirement is I want to submit the cart request-quote form 1 time after page load?

You may use localStorage for this.
Take a flag in set some initial value of it.
When the form submits update it's value.
By checking the same you can avoid getting submit.
<?php if(!isset($_GET['updated'])) { ?>
<script>
if(!localStorage.getItem('isFormAlreadySubmit')){
jQuery(document).ready(function($) {
jQuery("#yith-ywraq-form").submit();
localStorage.setItem('isFormAlreadySubmit', true);
});
}
</script>
<?php } ?>

You can move $_GET['updated'] to localStorage or sessionStorage, then you don't need to reload the page to ?updated=data page anymore.
localStorage will save updated value even when the browser is closed and reopened.
sessionStorage will save updated value but it will be cleared if the browser is closed.
That depends on you to choose which one. So I make a demo with sessionStorage which I prefer because when the user closes the browser, it will clear the updated value, maybe the next user in that device is another (public device). I also remove the check if(!isset($_GET['updated'])) condition.
<script>
jQuery(document).ready(function($) {
if (!sessionStorage.getItem('updated')) {
jQuery("#yith-ywraq-form").submit();
sessionStorage.setItem('updated', true);
}
});
</script>
Update: add live demo https://codepen.io/tuandaodev/pen/jOwvrRg?editors=1111

You need to use a server side session variable to check (duplicate)
Answer

Related

How to run a php file without refreshing the web page?

I have a problem. It is my full honor if anyone helps.
First, let me explain the workflow I want. My CMS is Wordpress. I have a webpage (views.php). In this page, I want to show a download button (id=” download-button”) just to users who has the role subscriber. In default, no one has the role subscriber. So, the button is hidden in default. When a user buys a specific product he gains the role subscriber. Now, suppose a user has opened views.php page as a tab in his browser. In this step, the button is hidden. After that, he opens another tab and buys that specific product and he gains the role subscriber. Now, if he refresh the view.php page, the download button is seen. But, I want the user to see the download button without refreshing the page. In this regard, I wrote button.php file to be called in ajax. However, it does not work.
My codes:
html code (written in view.php which is the place of download button):
<div id="div1"></div>
my javascript code (which is put inside view.php file):
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("button.php");
});
});
</script>
my button.php code:
<?php
if (check_user_role(array('subscriber'))) {
echo ('<button id="download-button">Download</button>');
}
?>
I should note that I have written check_user_role php function in views.php.
It would be my honor if you help.
Thanks in advance.
Milad
As stated by smartdroid in one of the answers above, you can subscribe an event listener function to the window.onfocus event. Try following:
document.addEventListener("DOMContentLoaded", function (event) {
window.onfocus = function () {
$("#div1").load("button.php");
}
});
I highly recomment you to read further into javascript events.
For plain javascript:
https://www.w3schools.com/js/js_events.asp
For jQuery:
https://api.jquery.com/category/events/
Hey you have to use Window setInterval() Method, what this method does it will fire in background at your time interval set.
You can call your ajax code to set/show your button
setInterval(function(){
$("#div1").load("button.php");
}, 3000);
Make sure once you do add this button put return false so it wont execute again and again not to increase load on webpage.
$(document).ready event runs only once after the DOM is loaded. So this event will not fire unless page is reloaded.
If the user is buying a subscription in another browser tab and then returns to the original tab, windows.onfocus event will fire.
So you can use window.onfocus event to check for subscription every time view.php tab becomes active, and then show the button when necessary. So you can use something like the following, in your view.php
$(document).ready(function(){
window.onfocus = function () {
$("#div1").load("button.php");
}
});
Add an iframe to your view.php that doesn't need to contain anyting nor be visible.
<iframe name="download" id="if_download" src="blank.html"></iframe>
Target the download-action to the iframe. With some JS:
function download(href) {
window.frames['download'].location = 'download.php?file=' + href;
return false;
}
You may need to wrap the download-action through a php-file to modify its header
download.php:
$file_name = $_GET['file'];
//validate file exists and *remove any ../ - simple:
if (strpos($file_name, '/') !== false) die('yeah right..');
header("Content-Disposition: attachment;filename=\"$file_name\"");
echo file_get_contents($file_name);
die();

document.getElementById.click() creates loop

I want to trigger a PHP script to run once the page is fully loaded while making sure it runs only once by checking if a session already exists or not. The problem I'm running into is that my script is creating a loop and page goes into reload frenzy.
I think shell exec triggers a refresh when the script finishes, which I need to keep because it sets some sessions which will trigger some divs to be hidden/shown after the reload.
Everything works if I click the button myself. How can I make the PHP trigger only once on page load based on the sessions values?
The reason I'm window.addEventListener is because the user will access this page based on a button on a previous page. But that causes the php to trigger first when the user clicks the button and only loads the page the button refers to after the script has finished.
Button
<form method="post">
<button id="CheckConnectionBtn" name="CheckConnectionBtn" class="CheckConnectionBtn" button>Start </button>
</form>
PHP
<?php
if(isset($_POST['CheckConnectionBtn'])) {
if (!isset($_SESSION['SEND_TRIGGER'])) {
$_SESSION["SEND_TRIGGER"] = "SET";
$output = shell_exec("/var/www/html/scripts/ping.sh");
$_SESSION["CONNECTION_CHECK"] = "$output";
} else {
echo "Do nothing";
}
}
?>
Script
<script>
window.addEventListener("load", function(){
document.getElementById("CheckConnectionBtn").click();
});
</script>

How to prevent a php page from browser back button?

I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.
You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.
Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })
Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.
Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>

Execute javascript function after php redirect

I have a page where a user creates an item to auction it. If he submits the item creation form, the browser automatically redirects him to the newly created page via the following line of php code:
header('Location: item.php?itemid='.$itemid);
I would like to display a notification right after the item creation (on the newly created page) saying that the item has been created. This is the (working) code I use to call the notifications:
<script type="text/javascript">
$(function(){
$container = $("#container").notify();
notifyItemCreation();
});
</script>
EDIT: I think people are misunderstanding the problem.
So my sellitem.php page contains a form to sell an item, if this is submitted it gets send to createitem.php, this is where I do the validation checks.
If everything is okay this is where I redirect to the newly created item.php?item='$itemid' page. I want on this (item.php?item='$itemid') page the notification to be displayed.
EDIT2: I do know how to create the item.php?itemid='$itemid' page, this gets done perfectly, it is the notification to appear that is the problem. I am using the notifications from http://www.erichynds.com/blog/a-jquery-ui-growl-ubuntu-notification-widget
Can the people who are downvoting also explain why they are.
You can use session variables. In the next request if a certain variable exists or indicates that the current item is new, you can echo the script tag and unset the variable.
You could just wrap the JS in a condition
<?php if(is_numeric($itemid)){ ?>
<script type="text/javascript">
$(function(){
$container = $("#container").notify();
notifyItemCreation();
});
</script>
<?php } ?>
You could use ISSET() as well

PHP and window.close in JavaScript

I have a problem. I have a page that when you click a button, a popup with a form is shown. So, I complete some data and I submit. What I want to do is, to submit the form, close the form and refresh the parent page. I don't want to do it with AJAX.
The problem is that in my parent page I have to refresh content with the input information of the form.
So when I refresh, sometimes the data is shown and sometimes not. Do you know why this could happen?
I just use onsubmit="refreshParent()" in my form. The info is stored always in my database, so I think the problem may be that sometimes the refresh catches the new info and sometimes not.
function refreshParent() {
window.opener.location.reload();
window.close();
}
I use this to reload the page that opened a popup window:
<script language="JavaScript">
<!--
function reloadParentPage() {
window.opener.location.href = window.opener.location.href;
if (window.opener.progressWindow) {
window.opener.progressWindow.close()
}
window.close();
}
//-->
</script>
By the way, the code above is called by a link or button in the popup page.
You have a race condition between the script doing the insert and the script reloading the parent.
The solution is to call refreshParent on the page after the submit - that way you know the data is in the database. You don't even have to do it on document ready - return a stub page that just defines and calls refreshParent in the head tag.
In PHP when you run post script, at the end, include this code :
echo '<html><script language="javascript">
parent.location.href="http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].'"; // or any other url
</script></html>';
This will output a javascript that will reload the windows.

Categories