When I try to run this script:
<form class="form-inline" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<button type="submit" name="buttonSubmit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['buttonSubmit'])) {
unset($_POST['buttonSubmit']);
echo "<script>alert(".isset($_POST['buttonSubmit']).")</script>";
echo "<script>location.reload(true);</script>";
}
?>
As a result, the page is refreshing in an infinite loop.
What is the reason?
How do I refresh my website only once?
When you use location.reload(true);, you do the same, programmatically, as clicking on the browsers "Refresh/Reload" button.
This will generate yet another "submit", over and over, hence always make the statement isset($_POST['buttonSubmit']) be true.
Here are a couple solutions:
location.href = 'page-to-load';
location.assign('page-to-load');
location.replace('page-to-load');
The Location.replace() method replaces the current resource, and after that the current page will not be saved in
session History, meaning the user won't be able to use the back button either,
to navigate to it and cause a repeated "submit", which normally will occur.
Note, if the 'page-to-load' is the same being already loaded, you can use location.href, e.g.
location.replace(location.href);
Yet another way would be, instead of rely on a client side script, to do a response redirect upon a form submittion, server side.
How to make a redirect in PHP?
This helped me:
Change location.reload(true); to window.location.href = '';
Related
i am trying above but message is displayed on php page.instead of reloading on index page AND DISPLAY MESSAGE ABOVE SUBSCRIBE FORM ITS REDIRECTING TO PHP PAGE.You can check on test site link attached.Form is on index
page.I tried to reload page through jquery onload and onclick onsubmit but didn't worked.below are test which i did.
//form is on index.html page
<!-- your form here -->
<form action="forms/subscribe.php"id="form" method="post">
<input type="email" name="email" placeholder="Enter your Email">
<input type="submit" value="Subscribe">
</form>
//form is on index.html page
My php page
<?php
// My Code goes here form to email
header.location(Location: /index.html)
?>
You cannot use js variable values after reload. You need to do things without reloading the page means you just need to update the content and control your HTML tags.
The above example you mentioned. They are not reloading the page, they are getting values from input box then hide that div. After hiding the div they are showing another div with the information.
For your solutions you can do the same but remember to reset input values for every request.
You can do it in PHP with page reloads if you store a message in the session. At the top of each page make sure that the first line is
session_start()
Then on the page that receives the data set a session message
$_SESSION['message'] = 'Some Value';
Then on your page with the form you check to see if the session has a message. If it does, display it and then clear it.
if(isset($_SESSION['message']) {
echo $_SESSION['message'];
session_unset('message');
}
some silly syntax error
using onsubmit="alert()"
<script>
function alert() {
alert("Thank you for contacting us. We will be in touch with you very soon.!");
}
</script>
on subscribe pageheader('Location: /index?message=success');
I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery
Re editing... this question has NOT been answered before!
I had understood that changing the contents of a current page with window.location replaced the cached version of the original page ( from the "last" history), so that you really couldn't go back with the browser BACK button. I had even seen this posted as a solution to preventing a malicious visitor from using the BACK button to to re-submit a mail form many times. But it is NOT workable because in the case of a mail form, the BACK button will just take the user back to the pre-POST version of the page.
So, I can use javascript to reset the form, disable the SUBMIT button, change to another page after success, or do whatever I want to the page. But its all for nothing if a simple click of the BACK button followed by SUBMIT causes the form to post again with just 2 clicks.
I know there are a lot of solutions to preventing malicious form resubmissions I can try, but I've had trouble getting them to work, and so I'd just like to know if removing the last history is a dead end. If there is a way, and it is pretty cross browser friendly, then I can just make it part of my scripted actions once my form is successfully processed, and my "thank you" page displays. Basically I'd want my "thank you" page's 'onload' event to either erase the last history, or in a browser compatible way disable the BACK button!
For what its worth, I've included code from simple test I've been working with. You can put some junk in the fields and hit submit. The vars are cleared in the PHP, the form fields are force cleared in javascript, and a new 'location' is invoked. Unfortunately, hitting BACK button will take you back to the "pre-posted" form, with all the strings you added still intact.
<!DOCTYPE HTML>
<html>
<head>
<title> Form Behavior Test</title>
</head>
<!--
<?php
$name = $email = $comments = "";
$formDone = false;
if ($_SERVER["REQUEST_METHOD"] == "POST" )
{
$formDone = true;
$name = $email = $comments = "";
}
?>
-->
<body >
<table border="1"><tr><td style ="text-align:right;" width=100%>
<form name="contactform" id="contactform" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" id="name" value="<?php echo $name;?>"><br>
Email: <input type="text" name="email" id="email"value="<?php echo $email;?>"><br>
<br>
<div align="center"> ---- <span class="error">*</span> Message ---- <br>
<textarea name="comments" id="comments" wrap="physical" cols="40" rows="10" ><?php echo $comments;?></textarea>
</div>
<input name="submit" id="submit" type="submit" value="Submit" >
</form>
</td></tr></table>
<script language="JavaScript">
if (<? echo ($formDone == true) ? 'true' : 'false'; ?>)
{
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("comments").value = "";
document.getElementById("submit").value="Disabled";
document.getElementById("submit").disabled=true;
// substitute with a thank you page
window.location = "http://google.com";
}
</script>
</body>
</html>
After searching pretty exhaustively, I don't believe there is any way to remove a page from history, except on the very latest browsers that support newer HTML-5 history methods. I'm still open to solutions but at this point I think the easiest thing will be for me to set a cookie anytime a successful email is processed by my PHP code. Then, I can also make the PHP or a javascript snippet look for the cookie and if found, I can take all kinds of actions... wipe out all filled in fields (as they would be if the BACK button is pressed), block the email, politely inform the user that he/she must wait (until my cookie expires) to send another email though the form, etc.
I didn't want to do this originally because the BACK button doesn't actually re-load the page, it just displays it. If there were a universal browser compatible way to make pages reached by back buttons actually re-load, this would never have been a problem to begin with. So even with a cookie, my defensive actions couldn't activate until the SUBMIT button is pushed. I guess I can live with that. Also, even today, some people are paranoid about cookies and turn them off. But if I want to be adamant about it, I can just detect when I can't set a cookie, and inform the user that cookies are required to use my email form. If that's too big a deal, oh well!
Thanks to those that contributed. The fact is, the LACK of answers is really a very useful answer sometimes. When I post on any stackoverflow forum and don't get any answers pretty quickly, its a good red-flag that things are going to get convoluted really fast if I don't consider an alternate approach! :-)
I am trying to send mails using PHP's mail() function.
I have a button (Send Mail), clicking on which the mail has to be triggered. Since PHP is a server side scripting language, I used Javascript to trigger the PHP function. A very unusual event occurs. Whenever I load the page, the mail gets triggered. So, I put alerts and echos to check if the code logic is correct.
Funny thing is that the mail does not get triggered when I click the button. Where am I going wrong?
Please see my code:
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
alert("<?php PHPFunction(); ?>");
}
</script>
<?php
function PHPFunction(){
echo("Inside PHP Function");
mail("to#example.com", "Help Mee", "Definitely Help me", "From:from#example.com");
echo("Mail Sent");
}
?>
PHP is a server side language, while Javascript is a client side language. I think you are confusing the two, and trying to mix their use in a way that would never work.
When the page is loaded, these steps occur in sequence:
The server interprets the PHP code in your page, and renders a page that does not contain any PHP code.
The client, viewing the page, does not obviously have access to any PHP function, because it sees only the result of the elaboration. It still can use Javascript to achieve dinamic behavior of the page (i.e. changes without refreshing), and things like AJAX to make requests to the server still without re-rendering the page.
<input type="button" onclick="jMail()" value="Send Mail"/>
The event onclick is indeed triggered when you press the button, but after the page has been fully loaded. At this time, all the PHP code has been already interpreted by the server, and there is no chance to execute it again without reloading the page.
EXAMPLE: here you can see the result of the elaboration of your code (under stdout). As you can see, the client is left with a PHP-free web page.
If you're looking for a way to trigger PHP code when an event occurs after the page has been loaded, I suggest you take a look at this question.
Also, this question on programmers.stackexcange.com could help you clarify the difference between client side and server side if it isn't clear.
You cannot trigger PHP from javascript that way. Create another PHP file, and call it using AJAX javascript requests.
<form method="post">
<input type="submit" value="Send Mail" />
</form>
<?php
if(isset($_POST)){
///do sent mail here
mail("to#example.com","Help Mee","Definitely Help me","From:from#example.com");
}
?>
PHP is a server side scripting language which has already been interpreted by the server and then sent to client(i.e browser) for interpretation of any client side script( ex JavaScript).
But if want a responsive webpage to be handled by your server try to use Form and inputs tags and their attributes to send your request back to server
But if you want a Quick way Try using AJAX.
every time you do
<?php PHPFunction();
you send the mail..
maybe you could play with something like
<?php
if(array_key_exists('postMail',$_POST)){
echo ("Inside PHP Function");
//if(empty($_POST['mailContent'])){/*angry blablabla*/}
mail("to#example.com","Help Mee",$_POST['mailContent'],"From:from#example.com");
echo ("Mail Sent");
die();
}?>
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
var xhr=new XMLHttpRequest();
xhr.open("POST","?");
var fd=new FormData();
fd.append("postMail","true");
fd.append("mailContent","fooooobar");
xhr.send(fd);
}
</script>
This is my initial page code
$_POST["i"] is the url that I have sent from the previous page and it works fine here. This is also the value that I am trying to send to the next page through the hidden field.
<form name="f1" method="post" action="window.open(/mydir/product-cat/brookbond?add-to-cart=89" rel="nofollow" data-product_id="89" data-product_sku="" class="add_to_cart_button button product_type_simple)">
<input type="hidden" name="k" value="<?php echo $_POST["i"]; ?>" >
<img src="<?php echo $_POST["i"]; ?>" />
<input type='submit'>
</form>
Receiving end code in the next page
<?php echo $_POST["k"]; ?>
It is not receiving any value and thus not printing anything.
Everything else works as expected.
Any help would be greatly appreciated.
NOTE: I cannot substitute the window.open function, it serves a definite purpose.
Not the most elegant of solutions, but maybe you can add it to the url of the window.open.
... window.open(/mydir/product-cat/brookbond?add-to-cart=89
& k="<?php echo rawurlencode($_POST["i"]);?>"
You can't send it the way you do. If you don't want to reload page and send post data then you need to use AJAX.
On this page you will find examples how to do it. You need to bind submit() event for form and then send ajax request to the page you want and process the results.
The other option is to use GET instead of POST but this window.open doesn't look good anyway.