Reset a form through javascript that is called via php - php

Ok I have googled for hours and found nothing that works. I need help desperately
I have got a form with the following elements in it.
<form action="sendmail.php" method="post" name="enquiry">
<table>
<tr>
<td>Name:-</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Company:-</td>
<td> <input type="text" name="company" /></td>
</tr>
<tr>
<td>E-Mail:-</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Contact:-</td>
<td> <input type="text" name="contact" /></td>
</tr>
<tr>
<td>Requirement:-</td>
<td><textarea name="msg"></textarea></td>
</tr>
</table>
<input type="submit" value="submit" onclick="return validation(this.form);">
<input type="reset" value="Reset" />
</form>
and the php has a line like this:
<?php
if(mail($to, $subject,$message)) {
echo "<SCRIPT LANGUAGE='JavaScript'>alert('Your Enquiry was sent successfully we will get back to you shortly');
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
</SCRIPT>";
}
?>
Then there's an "else" with the same code but a different message.
The problem is when it redirects back to the form page it still has the data in the fields. What I prefer is a clean form with no data filled in when the user returns to the page.
Please note I am a newbie to javascript so try suggesting a fix that would be easy to comprehend.
Thanks a lot in advance!

That's because you're going back in the history - browsers remember forms when you go back/forward.
What you are doing isn't a "normal" user experience - I would suggest you print out a nice looking page saying thanks in the "sendmail.php" file and then let the user navigate to wherever they want to on your site.

as Ed said, you are going back in history, and the browser remembers it.
Try this:
instead of this line: window.location.href='javascript:history.go(-1)';
write : window.location.href='RelativePathToActualForm';

Your Problem is with the javascript code:
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
Remove this code
EDIT:
Use this code:
if(mail($to, $subject,$message)){?>
<SCRIPT LANGUAGE='JavaScript'>
alert('Your Enquiry was sent successfully we will get back to you shortly');
window.location.href='/*YOUR FORM PAGE LINK*/';
</SCRIPT>
<?php }

After processing the form post you should redirect to another page (or again to your form) and display your message there e.g.:
php header("Location: form.php?formpostwassuccessful=1");
then the form page
if(isset($_GET['formpostwassuccessful']))
echo "Thank you. Your form was sent.";
also see redirect after post?

First look at example of using php session-based flash messages http://mikeeverhart.net/php/session-based-flash-messages/
Usual flow:
User fills in the form
Presses submit
Your php script sendmail.php validates the form
If there were some validation errors [set error message]
If there were some mail sending errors [set error message]
If everything is ok [set success message]
Call from php redirect to the form display page.
[set error|success message] - using the link provided above how to set the message.
Now important part every time you render your form, you should check for set messages, if there are some messages - display them.
How do those messages work?
It simply sets the message to session ($_SESSION) array, and then when the message is displayed, the message is unset from session.

Simple solution : just use jquery - a single line is to be usee in the head section to include jquery in your page.
The javascript snippet you gave should contain:
window.location="theform_page_address" ;
instead of
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
and in the form page address: add the following js snippet in the head section :
<script type="text/javascript">
$(document).ready(function(){
$('input').val('');
$('select').val('-1');
$('textarea').val();
});
</script>
EDIT: I assume your form has input and textarea elements which have a blank default value, , and select elements that have -1 as the value for the default option.

Related

capture html source code in jquery or javascript

I tried searching this but found no good solution.
My question is I have a HTML form with few text boxes. Once the user enter details and press submit I want to send this same HTML form to administrator email. The problem is I can not get the HTML markup with values. Is there any suggestion.
example
<div id="user_form" action="" method="post">
<form onsubmit="return validate_me();">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="test" id="test"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="send" id="send" value="Send"/>
<input type="hidden" name="html_data" id="html_data"/>
</td>
</tr>
</table>
</form>
</div>
So once user click on send button I want to send whole form with values to server then I can send it to admin email. How can I do that.
I tried following
<script type="text/javascript>
function validate_me(){
("#html_data").val($("#user_form").html());
}
</script>
But above send only markup without text box value.
Only above works in IE 9. fail in safari 5.1.7 and FF 23
Any suggestion would be greatly appreciate. Also I tried output buffering but I also did not help to send form element's values.
just submit your form
function validate_me(){
$('#user_form form').submit();
}
note: add action attribute to your form tag
Your updated code try this 1 and let me know if it not works.
<div id="user_form" >
<form onsubmit="return validate_me();" method="post" action="SOME_ACTION_URL">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="test" id="test"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="send" id="send" value="Send"/>
<input type="hidden" name="html_data" id="html_data"/>
</td>
</tr>
EDIT
<script type="text/javascript>
// on ready fill the value and then submit it
jQuery("document").ready(function () {
jQuery("#html_data").val($("#user_form").html());
})
function validate_me(){
// YOUR code MUST be return
return true;
}
</script>
I've just noticed this same problem. What I wanted to do was switch one form with another form yet retain the values the user has entered into the form, such as a message. I tried outputting the form via console.log and noticed all of the form shows up except the user entered data.
I was attempting to have a second form appear to make sure the user agrees to what they are about to do with a button to go back and make changes. I redisplayed the original form and TADA David copperfield magic, the form is there without any of the content in the inputs. (a text input and textarea)
I am not sure why this happens, I am guessing all I can do is store the user entered data in a namespaced global before trying to save the form data, then redisplay the form and replace the users content one field at a time.
What is the reason for this does anyone know? It must be something about how the inputs work in browsers.

Stay on same page, don't reload

Here are two forms fregister and register. In first form I am taking input of name,username and checking the availability of username by clicking on Check user id button.If username is not available I am displaying message with the help of php and want to show this message to user with the fields he filled before.
<?php RegFormCrAndValid($name,$username,$email) {?>
<form name="fregister" method="post">
<table>
<tr><td>Name</td>
<td><input type="text" id="name" name="name" value ="<?php echo $name;?>" onChange="ValidAllAlpha()" required></td>
<td><span id="ErrorName"></span></td></tr>
<tr><td>Username</td>
<td><input type="text" id="user" name="UsrText" value="<?php echo $user;?>" required onblur="SetNextElement()"></td>
<td><?php echo $_SESSION['ErrorUserMsg']?></td> <td><input type="submit" name="CheckUsr" value="Check User ID"></td> </tr> </form>
In second form, the user will register here first checking the availability and then submission will take place by clicking on register.In this form too if user has not registered successfully then I want to show message with fill fields.
<form name="register" method="post">
<td style="display:none"><input type="text" id="fname" name="fname" required></td>
<td style="display:none"><input type="text" id="fuser" name="fuser" required></td>
<tr><td>Email</td>
<td><input type="email" id="email" name="email" value="<?php echo $email;?>" onChange="ValidateEmail()" required></td>
<td><span id="ErrorEmail"></span></td></tr>
<tr><td><input type="submit" name="submitForm" value="Submit" onClick="ValidationCheckOnSubmit('register');return false;"></td></tr>
</form>
</body>
</html>
Two rows are not displayed here because they are taking the values of name and username from the form fregister with the help of javascript and then displaying them.
JavaScript Codes // validations are there, here I am mentioning the code for passing values to fname and fuser
function SetNextElement()
{
document.getElementById('fname').value = document.getElementById('name').value;
document.getElementById('fuser').value = document.getElementById('user').value;
}
<?php }?> //RegFormCrAndValid($name,$username,$email) this function getting closed over here
php coding
if(isset($_POST['CheckUsr']))
{
if(IsUsernameAvail($_POST['UsrText'])) //IsUsernameAvai checking for the username availabilty return true if available as false
{
$_SESSION['ErrorUserMsg']="<font color=red>This Username Is Available</font>";
}
else
{
$_SESSION['ErrorUserMsg']="<font color=red><--Username is not available</font>";
}
}
if(isset($_POST['submitForm']))
{
if(IsUsernameAvail($_POST['fuser']))
{
echo 'You have been successfully registered';
}
else
{
$_SESSION['ErrorUserMsg']="<font color=red><--Username is not available</font>";
RegFormCrAndValid($_POST['fname'],$_POST['fuser'],$_POST['email']);
//RegFormCrAndValid($name,$username,$email) is the function in which whole html and javascript code is there to create and validate the form.
}
}
else{ if(isset($_POST['CheckUsr']))
{
RegFormCrAndValid($_GET['name'],$_POST['UsrText'],'');
}
else RegFormCrAndValid('','','');
}
My problems
While on clicking CheckUserId button I want the page to stay over there only, why after clicking it doesnt stay on same page with all field fill as they were filled by user. It should just perform the check, why does page reloads?
If I am able to stay over the same page then I dont need to call RegFormCrAndValid($name,$username,$email) this function again to rebuild my form, is it possible to stay there with filled fills and not calling function.
I want to eradicate the use of fake columns to show username and name again because in real registration form there are going to be lot of fields and I cant have fake calling or assignment for all of them.
I dont want to use ajax or jquery, want to achieve everything through javascript,php and html.
When you are clicking on <input type="submit" name="CheckUsr" value="Check User ID"> the form is being submitted, because thats what clicking on submit buttons do, unless you have javascript to block it and do something else.
When a page is being submitted back to the server, the page will reload.
Now, over to your basic goal : you must understand that the actual checking which you are doing to determine whether username is available or not, is on the server side, that is, the logic resides on the server. Whereas, the form which the user is typing the username on, is on the client side, that is residing on the users computer, being displayed through the browser. Now once the user types the name, you somehow need to pass that data over to the server side for it to do the checking and perform actions accordingly. Therefore you have two options:
a) Submit the form as you are now, and use server side php code to collect all the data filled by the user and populate them back again
b) donot submit the form, just make an ajax request to a php script, which will take as input the username and return to you either a true or false response which you can catch using javascript, and accordingly allow the form to be submitted or not submitted.
In that case either on the submit buttons onclick event or the forms onsubmit event trigger set a javascript function to make the ajax request and "return false" if the ajax request returns false or "return true" if the ajax request returns true. Also in the "false case" you can use getElementById to set the error message for the user.
Answer for (a)
You are using form submit action
Default behaviour of form submit is it will reload the page. You have to suppress the default behaviour of form submit by using return false .But it is not recommended.. you can use AJAX
Sample Code
$('#yourFormId').submit(function () {
//business logics here
return false;//to avoid page reload
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />

form session data not posting, sessions working

I've been tinkering with this for a few days. Checked out all the posts related and still can't quite get it to work. Anyone able to take a look and steer me in the right direction?
I have a site where everything gets loaded into a div on a page.
everything is working great except the form data.
I can load the session data for a test and it works fine, however i can't seem to get any of the entered form data.
i have the session_start(); included at the top just under the opening php tag in connection.php. connection.php is required on each page.
connection.php beginning.
<?
session_start();
Here are some code samples from addvehicle.php (not posting it all as it's huge and the rest is not relevant, can if need be though)
...
<script type="text/javascript">
$(document).ready(function()
{
$('form#newvehicleform').submit(function()
{
<?php
$trucknumbera=$_POST["trucknumber"];
$_SESSION['trucknumber']=$trucknumbera;
$_SESSION['info']="this is some info";
?>
$("#mainwindow").load("addvehiclepost.php");
return false;
});
});
</script>
.....
<form id="newvehicleform" class="newvehicleform" method="post" action="<?php echo $PHP_SELF;?>">
<table>
<tr>
<td>
Truck Number
</td>
<td>
<input name="trucknumber" class="validate[required,custom[number]]" type="text" id="trucknumber" autofocus autocomplete="off" required />
</td>
</tr>
<tr>
<td>
<br>
<input type="submit" id="submit" class="s-submit" alt="Submit" value="Submit">
</td>
</tr>
</table>
</form>
the test of, addvehiclepost.php
require ('./connection.php');
echo "<br>info: " .$_SESSION['info']. "<br>";
$trucknumber=$_SESSION['trucknumber'];
echo "<br>trucknumber: " .$trucknumber;
and here is the output i get from addvehiclepost.php
info: this is some info
trucknummer:
so you can see it's passing the $_SESSION properly and that function is working however I just can't get it to pass the submitted for data.
Anyone have any ideas on getting this to go?
Thanks in advance.
-Colin.
When you execute your first script with PHP, there is no form data.
And the PHP fragment executed there does not do anything besides transfering an empty POST value (NULL) to a local variable and then to the session array.
I think you think that this PHP code gets executed when the javascript is called, but this is not the case! First all PHP is executed, and the result is echoed back to the browser. Then the page is rendered and javascript is executed.
So the PHP part of your code does copy an empty value (and sets a static one as well, that's what you see) at the time the form page is first loaded by the browser.
Then javascript acts. Which would mean in your case that there is no form POST request, but simply a GET request for the addvehiclepost.php script. No POST request means no $_POST data. Which isn't accessed in the loaded script anyway.
I don't know if you are able to fix this, but I hope I enabled you to understand the structural error of your code. I have seen this with about any newbie I know.

Submit button is not listening to isset handler

I don't have many instances that PHP craps out on me. But this is surely one of them, I have checked through this for an entire day and figured it might coem from a 3rd party. But a symptom that tells me this error is random is that I cannot even try to set a string variable to post back from the submit. Neither isset nor empty works to capture the event. When I press the submit, the only thing I see is my txtbox variables get shot up into the URL. but NO validation occurs.
So right now now I have a submit button for a login page as follows:
<form action='Login.php' method='post'>
<table align="center">
<tr><td>Username</td></tr><tr>
<td><input type="text" name="txtUsername"/></td></tr>
<tr><td>Password</td></tr><tr>
<td><input type="text" name="txtPass"/></td></tr>
<td colspan="2"><input type="submit" name="btnLogin" ID="btnBlueTemp" value="Sign in!" /></td></tr>
<tr><td class="errorLogin"><?php echo $Error;?></td></tr>
</table>
</form>
I've called the necessary POSTs and here is the event.
$txtUsername = $_POST["txtUsername"];
$txtPass = $_POST["txtPass"];
$btnLogin = $_POST["btnLogin"];
if(isset($btnLogin)){
$Error = "ok";
}
What could be causing a problem that is not letting my button handler be caught? I am using Internet Explorer 9.
Do not use submit button to check that the form has been submited. either add a hidden form field and check that if its set, or use some other mechanism. You will not have this problem in firefox, but in IE you will.
You are doing it wrong. When you use $btnLogin = $_POST["btnLogin"]; , you are actually setting the variable. So your script will get executed even you hit the url from address bar without hitting submit button.
Instead use -
if(isset($_POST['btnLogin']){
// do stuff
}else{
// do other stuff
}

Switching my form submit to ajax-can I just change onsubmit action?

I see lots of jquery tutorials from building the submit form from scratch, and that is cool, but I'm wondering if I can convert my existing form.
I'm using a typical form, and already have an email and blank values checking in place. Right now, on submitting the form, the user is taken to the confirmation php page withing form-submit.php.
I'd like to change that to just giving a user a line on the current page "Your form has been submitted"
Here is my form:
<form name="theForm" action="/contact-form2.php" method="post" onsubmit="return formCheck(this);" >
<table class="formTable" cellpadding="3" cellspacing="0">
<tbody><tr>
<td align="left"><b>Name:</b></td>
<td><input name="name" id="name" size="25" value="" type="text" /></td>
</tr>
<tr>
<td align="left"><b>Email:</b></td>
<td><input name="email" id="email" size="25" type="text" /></td>
</tr>
<tr>
<td align="left"><b>Confirm Email:</b></td>
<td><input name="email_confirm" id="email_confirm" size="25" type="text" /></td>
</tr>
<tr>
<td align="left"><b>Subject:</b></td>
<td><input name="Subject" id="subject" size="35" value="" type="text" /></td>
</tr>
<tr>
<td align="left" valign="top"><b>Message:</b></td>
<td><textarea name="Message" id="message" cols="30" rows="6"></textarea></td>
</tr>
<tr align="left"><td> </td><td><input type="submit" value="Submit" onclick=" return checkEmail();" /> <input type="reset" value="Reset" /></td></tr>
</tbody>
</table>
</form>
So is it possible to just change the on submit or onclick to be able to both submit the form through the external php file, and stay on the same page?
You can convert the existing form, but it is not as simple as just changing the onSubmit or onClick events.
When you use jQuery or another Ajax library to do a callback you are loading new content into the existing page. To do that you need a labeled block, usually a div, to contain any data to change. You also need to write the wrapping code for the callback to send it and to update the page's HTML.
The quick and dirty version on your form would be to wrap the table in a div tag and the Ajax call return new HTML for that div. Your new target for onsubmit would be the wrapping code for the callback I described above.
You still need to do all the work to use jQuery and point it to the right places. As I use prototype.js I can't really detail the jQuery process, but all the tutorials you are reading can.
Yes it is. I would suggest introducing some Javascript (the following example uses jQuery):
<script type="text/javascript">
// when the DOM is ready
$(document).ready(function() {
// bind some code to the form's onsubmit handler
$('form[name=theForm]').submit(function() {
if(formCheck(this)) {
// $.post makes a POST XHR request, the first parameter takes the form's
// specified action
$.post($("form[name=theForm]").attr('action'), function(resp) {
if(resp == '1') {
alert('Your form has been submitted');
} else {
alert('There was a problem submitting your form');
}
});
}
return false;
});
});
</script>
The return false at the end of the above submit handler prevents the browser from loading up the form's action (following the url) in the traditional way. Furthermore, if Javascript is not present, the form will submit the old school way, so essentially you have added a layer of usability above your standard form implementation which degrades gracefully.
I would like to point out that it is always a good idea to provide the user with realistic feedback. That is to say, the ajax posting of the form can capture some indication of this from the server, in the above example I have assumed that a '1' means that the record was successfully saved, and a '0' means it was not saved (the query failed, etc.). The message displayed to the user depends on this outcome.
Yes, you can change the onclick form action to a javascript:myajaxsubmit() function.

Categories