I have a simple button that hides once the event is triggered
<?php
//Define attributes
echo'<input type="submit" id="toggler" name="add_friend"class=button
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>';
?>
//Hide the button
<script>
var hidden = false;
function action() {
if(!hidden) {
document.getElementById('toggler').style.visibility = 'hidden';
}
}
The above works as it should no problems , However when I add form to get method=POST for the button does not hide nor does my POST make it to $_POST['add_friend']
echo ' <form method="post" >
<input type="submit" id=toggler name="add_friend" class="button"
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>
</form>';
How can I make correct this so that the button hides and my POST is passed on to my isset code please .
if (isset ($_POST['add_friend'])){
//rest of my code once the button is clicked and hidden
Thanks in advance .
Your JS is most likely hiding the element. Then your form gets submitted (the POST), only for the page to refresh and the button reappear.
It seems to me that you want to hijack form submission and process the request with ajax.
The following example code shows a similar problem with the Php form processing. You could adapt to your liking (I have left out the required Javascript):
<?php
$feedback = null;
$people = array(
1 => 'Samuel',
2 => 'Fred',
3 => 'Roger',
4 => 'Mavis'
);
$friends = array(3); // i.e. Roger
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$add_friend = isset($_POST['add_friend']) ? $_POST['add_friend'] : null;
if(array_key_exists($add_friend, $people) && !in_array($add_friend, $friends)) {
array_push($friends, $add_friend); // You probably want to save state here
$feedback = 'Added ' . $people[$add_friend] . ' as friend.';
}
}
?>
<?php echo isset($feedback) ? $feedback : ''; ?>
<form method="post">
<?php foreach ($people as $key => $person) { ?>
<button name=
"add_friend" onClick=
"action();" value=
"<?php echo $key ?>"
<?php echo in_array($key, $friends) ? 'disabled' : '' ?>
>
Friend <?php echo $person ?>
</button>
<?php } ?>
</form>
Checkboxes may be a better fit than buttons here.
A couple things wrong with this. You have an extra double quote before 'method' in your form, and should also add action="#" to the <form> tag. This tells the browser to send the result of the form to the current page. It's also good practise to add a hidden field to send your data, rather than adding it to the submit button. Try this and see if it works.
if (isset($_POST['add_friend'])) {
var_dump($_POST['add_friend']);
}
echo '
<form method="post" action="#">
<input type="hidden" name="add_friend" value="'.$output1['username'].'">
<input type="submit" id="toggler" class="button" value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</form>
';
Bear in mind this will essentially reload the page, so if you want to make an asynchronous request (EG, send some request without loading the page again) you will need to look into a solution with AJAX.
unless you didn't supply more information or copy/paste everything, you seem to have extra quotations here:
echo ' <form "method="post" >
Wrapping the input in a form will natively submit the form as well as fire your javascript. If you want to use an ajax solution, tie into the submit event and prevent the default action. (using jquery here):
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
// serialize() will get the form data, which can be used in ajax call
console.log( $( this ).serialize() );
});
Related
I wrote this form using html and PHP on my webpage. This form receives a number as input. and adds the desired number to 2. And prints the output.
For example, if we put the number 5 at the input and press the submit button , The page refreshes to this URL : mysite.com/page1/?sen=5&sub=Submit
And the number 7 is printed on the output.
So far so good. But when we refresh the page in this case , The submitted information will not be deleted and the url will remain "mysite.com/page1/?sen=5&sub=Submit" .And the output is not cleared and still remains 7.
In this case, I want the page to return to its original state, (mysite.com/page1) . And the output is cleared.
what's the solution?
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php if ( isset($_GET['sub'])){
//$sen1=0;
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
else {
echo $sen1 + 2; }
}
?>
This can easily be achieved with Javascript. Here's a very basic example.
You could make this a function. Then call it once to invoke it on a page refresh, and if you want to invoke it on button actions, you can use an html onclick attribute, or an event listener.
<script>
function clearFormAndParams() {
// Target each form input and set the value to "".
document.querySelector("input[name='sen']").value = "";
// Split the url by the "?" and then set the value to the first half.
window.location = window.location.href.split("?")[0];
}
clearFormAndParams(); // runs on refresh
var submitButton = document.querySelector("input[name='sub']");
submitButton.addEventListener("click", function() {
clearFormAndParams();
});
</script>
You could achieve your goal by modifying your code to store the results of calculation in a cookie / session variable and redirecting to the same page without the extra parameters like so:
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php
if ( isset($_GET['sub'])){
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
setcookie("result", $sen1 + 2);
header("Location: " . $_SERVER['PHP_SELF']);
}
echo $_COOKIE['result'];
?>
I have this form:
<form action="" method="post" name="my_form">
<input type="text" name="my_input">
</form>
You can write some text and the submit by pressing the enter key.
My problem: When you press the enter key multiple times, it'll also sent multiple times to my server.
There are solution like this:
onsubmit="my_button=true;return true;"
But these solutions require a submit button.
Is there a way to do this without adding a (hidden) submit button?
If you want to be absolutely sure, for example, submitting the form twice can cause severe damage/cause malicious things to happen, then you need to check this serverside. One rule of webdevelopment and general development is to never trust your end-user, and by simply blocking the form using JavaScript, you cannot be assured that a malicious user won't be sending the form twice by getting around the JavaScript.
What you can do is something like this:
Important: This is just a proof of concept example to explain the idea, this is not a 100% bulletproof solution.
Form
<?php
session_start();
$_SESSION['nonce'] = random_number();
?>
<html>
...
<form method="post" action="process.php">
<input type="hidden" name="nonce" value="<?php echo $_SESSION['nonce']; ?>" />
... other form elements ...
</form>
...
process.php
<?php
session_start();
$nonce = isset($_POST['nonce']) ? (int)$_POST['nonce'] : 0;
$session_nonce = $_SESSION['nonce'];
if ($_SESSION['nonce'] != $nonce) {
die("Invalid nonce, double submission detected.");
}
$_SESSION['nonce'] += 1; // this will cause the previous check to fail on a second submission.
some like this :
<form onsubmit="send();" method="post" name="my_form">
<input type="submit" name="my_input" id="sub">
</form>
js code:
function send(){
$("#sub").attr('disabled', 'disabled');
$.ajax({
// data
success: function(data){
$("#sub").attr('disabled', false);
}
});
}
Like this (untestet):
var formSubmitted = false;
document.getElementById('my-form').addEventListener('submit', function(){
if(formSubmitted === false) {
formSubmitted = true;
return true;
}
return false;
});
You could disable the button once it's set so the User cannot click it again
<form action="" method="post" name="my_form">
<input type="text" name="my_input" <?php if(isset($_POST['my_input'])) { print
'disabled'; } ?>>
</form>
I've done this so often before on different websites, but can't get it to work now.
I've got a simple form that posts perfectly well using a submit button, but for a specific reason I actually need it to submit via a url link instead. I'm using submit(). The form submits, but the data isn't posting.
What am I missing?
<html>
<body>
<?
if(isset($_POST['bar'])) { echo 'testing button<br>'; }
if(isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) { oForm.submit(); }
else { alert("DEBUG - could not find element " + formId); }
}
</script>
</body>
</html>
The form starts to submit, then the href of the link is followed, and this cancels the form submission.
If you are using old-style onclick attributes, then return false; at the end to prevent the default action.
You would, however, be better off using a submit button (you are submitting a form). You can use CSS to change its appearance.
Try this code :
<html>
<body>
<?php
if (isset($_POST['bar'])) {
echo 'testing button<br>';
}
if (isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) {
oForm.submit();
}
else {
alert("DEBUG - could not find element " + formId);
}
}
</script>
</body>
</html>
try to submit form with form id in jquery
<a class="submit">Post Directly </a>
$('a.submit').click(function(){
$('#fooform').submit();
})
I have created a form that has a subit button which will submit the for to a database, and a email button which will run a .cgi script to process the mail. Im having trouble getting the submit button to work.
here is the form buttons
<FORM name="drop_list" method="POST" >
<input name="emailForm" type="button" id="emailForm" onClick="sendFormEmail()" value="Email">
<input name="add_patient" type="button" id="add_patient" onClick="addPatient()" value="Add Patient">
</FORM>
And here is my javascript
function sendFormEmail() //email form
{
alert ("Email, this is disabled atm");
document.drop_list.action = "html_form_send.php"
document.drop_list.submit(); // Submit the page
return true;
}
function addPatient() //Post form to data base
{
alert ("Post to database");
document.drop_list.action = <?php echo $editFormAction; ?>;
document.drop_list.submit(); // Submit the page
return true;
}
The sendFormEmail() works fine, but when I try to use addPatient(). The form will not submit and something in the document.drop_list.action = ; line completely breaks the java script.
Thanks in advance for your help.
-Gregg
You haven't shown the value of $editFormAction, but I'll bet it doesn't have quotes around it. So you need to write:
document.drop_list.action = "<?php echo $editFormAction; ?>";
If you checked in the Javascript console, you should have seen an error message about an undefined variable or undefined not having a php method. And then if you looked at the JS source, you would have noticed that the script name doesn't have quotes around it, like it does in sendFormEmail.
So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>