Javascript redirect based on form input - javascript

I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards

You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.

in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.

To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.

Related

How can I display something from another page by using HTML/Javascript?

I have looked around for answers to this question but either do not understand the logic of the other answer, or have done something wrong trying to incorporate those answers.
I have 2 pages of HTML, where the first page has this form
<form class='registerbutton' action='registration.php' method = "POST">
<input type='email' name='email' placeholder='Email'>
<input type='submit' value='Register'>
<script> localStorage.setItem("useremail",email);</script>
</form>
When I do not use the method="POST" I can see in the URL that the email value is added onto the URL and therefore that this form works. However, in my next page I have this:
<body>
<script>
var test = LocalStorage.getItem("useremail");
document.write(test);
</script>
</body>
However, this does not work. I have also tried <?php echo email;?> but that also does not work. I am sorry if this is a trivial question. I am more used to other programming languages and am new to web development.
This solution will work client side only. Try it should work fine, it should work fine. If any thing else then let me know.
Page 1
<form class='registerbutton' action='registration.php' method="POST">
<input type='email' name='email' placeholder='Email' id="emailId">
<input type='submit' value='Register'>
</form>
<script type="text/javascript">
var email = document.getElementById('emailId');
email.addEventListener("keyup", function(event) {
localStorage.setItem('useremail', event.target.value);
});
</script>
Page 2
<body>
<script type="text/javascript">
var test = localStorage.getItem("useremail");
document.write(test);
</script>
</body>
SERVER SIDE
<?php
echo $_POST['email']; // In case of post and $_REQUEST['email'] will work for both.
?>
Since your method is POST, so you can access your email with PHP by the following:
<?php echo $_POST['email']; ?>

Submit form using anchor tag

I'm currently working on my webpage where I'm using an anchor tag to process the request. Here is the portion of my code:
I AGREE
It works okay. However, I added an input field and I have to include that in my process on "?redirect=Pro". My input field value is not being processed because the form is not being submitted/processed. I already tried the:
<form id="discount">
<input type="hidden" id="coupon_applied">
</form>
<a id = "agree" onclick="document.getElementById('discount').submit()" href="?redirect=Pro" target="_blank">I AGREE</a>
But I still can't get it to work.
I can't remove the ?redirect=Pro because that's where all my process is happening.
Any advice on how I i will modify my code to accommodate this would be much appreciated.
EDIT: This is a preview of my pricing.php file for more info:
<?php
session_start();
$link=$_GET['redirect'];
$discount_amount = $_POST['coupon_applied'];
if ($link == 'Pro')
{
echo "<script type='text/javascript'>alert('$discount_amount')</script>";
}
?>
<form id="discount" action="pricing.php" method="post">
<input type="hidden" id="coupon_applied">
</form>
<a onclick="document.getElementById('discount').submit()" href="?redirect=Pro" target="_blank">I AGREE</a>
With my current code, echo is returning blank/null.
You should use a method and action in your form like: <form action="/action_page.php" method="post">

Pass data to another page and submit form on that page

I'd like a button on page1.html. This button will pass data to page2.html which has a form on it, load that data into the form, and submit the form on page2.html. Is this possible? How would it be done? I can't seem to find any examples of this.
Thanks!
Of course the best thing to do is to use a backend... but I guess you wouldnt be asking if you had that option.
one thing you can do is use the anchor in the URI, like: /page2#?field=value&fld=val
Then on page load, check for an anchor tag and process it:
$(function(){
let hash = window.location.hash.substr(1);
})
Here's a plunkr to get you off the ground: https://plnkr.co/edit/u9fPGFZedXGmKbbdXVvy?p=preview
So once you have the hash you would parse it to JSON and configure your form with it.
It isn't obvious that it works because of how these fiddle-like sites operate. But it does work! To check it out, open the preview in separate window mode, and copy the url, open that url in a new tab, and add a sample hash on it, and press enter so it takes. then reload the page.
I ended up using PHP's Post method:
From originating page1.php page:
<form action="page2.php" method="post">
<input type="hidden" name="MyName" id="MyId" value="MyVal">
<input type="submit" value="Post to page2">
</form>
In receiving page2.php page:
<?php if (!empty($_POST)) : ?> // Check for Post data
<script>
document.getElementById("MyId").value = '<?php echo $_POST["MyName"]; ?>'; //update form on page2.php by field ID
document.getElementById('FormToSubmit').click();
</script>
<?php endif;?>
Works perfectly
You can simply add (target="_blank") to form tag and you can get data in specific action page
<form action="test.php" method="post" target="_blank">
<input type="text" name="test" />
<button type="submit" name="submit">Submit</button>
</form>

How to prevent data submission after refresh [duplicate]

I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}

Submit button with POST instead of using HTML form

I have a form inside a form and this makes the top form unresponsive. When I take off the second form (which is inside the first form), the first form works. This is the second form I have:
<form action="imgupload.php" method="post" enctype="multipart/form-data">
<h3>Upload a new image:</h3>
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup">
</form>
Since this makes the first form not work, I was wondering if I can take off the form fields and then the submit button can send the form data to the imgupload.php like this.
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup" action="imgupload.php" method="post" enctype="multipart/form-data">
This does not work now. Is there a way I can get this working? If not, what's an alternative way to send this data to the other php?
Since you are uploading files, have a look at Ravi Kusuma's Hayageek jQuery File Upload plugin. It's simple, it's a Swiss Army Knife, and it works.
Study the examples.
http://hayageek.com/docs/jquery-upload-file.php
Ravi breaks down the process into three simple steps, that basically look like this:
<head>
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet"> // (1)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2)
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3)
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final step is to have the PHP file specified in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename specified in the jQuery code block.
Don't forget to check out the server-side code from the Server Side tab -- you need both parts (js and php).
Looking at your question again, you will probably want to use this functionality as well:
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
}
or
dynamicFormData: function(){
return {
newID: $("#newNID").val(),
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
formRole: $('#formRole').val()
};
These will appear on the PHP side, thus:
$newID = $_POST['newID'];
$subj = $_POST['newSubj'];
etc
As with any plugin, resist the temptation to just plop it into your code. Do a couple of quick-and-dirty tests with it first. Kick its tires. Fifteen minutes will save you two hours.
And don't forget to verify what was uploaded. You never know when a developing country black hat might be trying to get a new account.

Categories

Resources