HTML hyperlink with Javascript onclick event - javascript

how to make a hyperlink to download the upload file and by the same time it updates its database?
For now I can download the file but it doesn't change the file status.
Here is my code
Docx
<script type="text/javascript">
Cufon.now();
function runMyFunction() {
<?php
mysql_query("update report_upload set status=1 from report_upload where year='$year' AND area='$area'",$conn);
?>
return true;
}
</script>
try1
.html
<form id='login' action='adminReportDownload.php' method='POST' enctype='multipart/form-data'>
<input type="hidden" value="<?php echo $area;?>" name="yeara">
<input type="hidden" value="<?php echo $year; ?>" name="yeary">
<input type="hidden" value="<?php echo $abc123; ?>" name="abc123">
<input type="submit" name="submit" id="submit" value="Download">
</form>
.php
$a = $_POST['yeara'];
$b = $_POST['yeary'];
$c = $_POST['abc123'];
$file_path = 'reports/'.$c;
$sqlABC = "UPDATE report_upload SET status='1', usedBy='$sesId' where year='$b' AND area='$a' ";
$eviABC = mysql_query( $sqlABC, $conn );
header("location: reports/$c");

Because PHP is server-side, it is executed before your browser displays your web page. Thus, your JavaScript function runMyFunction contains nothing but a return true; statement.
Especially since trying to do server-side operations from the client-side is a bad idea, a better solution may be to have the link point to a PHP page that sends the file and updates the database at the same time.
For further reading, this question about PHP readfile may be helpful.

you can achieve this by send post request to server when click on the link.
on the eventhandler, prevent the default behavior by e.preventDefault(); e.stopPropagation()
write an ajax method to post the request to sever
on serverside, update the database, write the file to frontend.

Related

How to run JS function on button click, using PHP form data?

I have got a form on my WordPress homepage that takes one input.
<form method='post' action='<?php bloginfo('url'); ?>/test123/' >
Name: <input type="text" name="name" required="required">
<input type="submit">
</form>
When submitted it redirects and passes the input to the test123 page (the page has a custom php template). If I add Hello <?php echo $_POST["name"]; ?> then it works without issue.
However, I have a JavaScript function that should run after the submit button is clicked. The users input name needs to be used inside the function.
My first thought was to use onclick="test();" but I don't believe that will work for calling the function on a different page, and I still have the issue of passing the PHP data into the JS function.
I've tried using <script type="text/javascript> .... </script> in test123 page's php template file with no luck.
Edit:
<?php /* Template Name: test123 */ ?>
<?php get_header(); ?>
Your email is <?php echo $_POST["email"]; ?>
<script type="text/javascript>
function testing() {
console.log(<?php echo $_POST["email"]; ?>)
}
testing();
</script>
<?php get_footer(); ?>
If you using jQuery in Wordpress
$('form').submit(function(e){
var name = $(this).find('input[name=name]').val();
// do smth with name
return true;
});

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";
}

save value when going from one html to another

I have a value on a textBox on html:
<input type="text" id="Key" name="Key" required />
then I send action to php and I do this from php:
<?php
header("location:./setupDatos.html");//echo "2"; //first time activation
echo '<input type="text" value="' . $varKey. '" />';
The problem is, if I remove this line
header("location:./setupDatos.html");//echo "2"; //first time activation
it shows me a blank page with the key I sent to php (as expected)
but with the line, it changes to new html and the input with the key sent is nowhere. How can I send that value from first html to the next html?
The HTTP protocol is stateless, meaning it can't "remember" older post data. However you can use the session to simulate a state.
Try doing something like:
<?php
session_start();
$_SESSION["oldpostdata"] = $_POST;
header("location:./setupDatos.html");
Not sure what the point is here. An html page wouldn't normally be able to do any server-side processing. If it were able to however you'd access your old post data like:
setupDatos."html"
<?php
session_start();
$oldPostData = $_SESSION["oldPostData"];
unset($_SESSION["oldPostData"]); // To only "flash" the data and not have it persist
$id = $oldPostData["Key"]; // Probably
Alternative way to "forward" the post data taken from this question:
<!DOCTYPE html>
<html>
<body onload="document.forms[0].submit()">
<form action="new-location.php" method="post">
<?php foreach( $_POST as $key => $val ): ?>
<input type="hidden" name="<?= htmlspecialchars($key, ENT_COMPAT, 'UTF-8') ?>" value="<?= htmlspecialchars($val, ENT_COMPAT, 'UTF-8') ?>">
<?php endforeach; ?>
</form>
</body>
</html>

taking Input field value in session variable and showing at action page

I have following code at s.php:
<?php
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['p'] = $_POST['p'];
}
?>
<form action="s2.php" method"post">
<input type="text" name="p"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
And At s2.php
<?php
session_start();
?>
<?php
echo 'This is especially for ='.$_SESSION['p'];
?>
After entering value in input field and clicking the submit button, it take to next page and change the browser link to some thing like /s2.php?p=inputvalue&Submit=Submit.
I want to show the value at s2.php that was entered in the input field at s.php.
I have placed the echo code, but nothing shows up (I have tested on different servers).
The problem is solved. Thank you.
Solution: at s2.php (action page) we have to use the following code:
echo 'This is especially for ='.$_POST['p'];
Thanks

Javascript redirect based on form input

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.

Categories

Resources