Form feedback without a page refresh - php

I'm getting my feet wet with form processing so bear with me. I have a basic HTML form and a script that sends mail. At the moment it sends and refreshes to give feedback. What I would like is if the feedback could be given without refreshing the page.
HTML
<html>
<head>
<title>E-Mail Form</title>
</head>
<body>
<form action="beta_sendmail.php" method="POST">
<p><strong>Name: </strong><br/>
<input type="text" size="25" name="name" /></p>
<p><strong>E-Mail Address: </strong><br />
<input type="text" size="25" name="email" /></p>
<p><strong>Message: </strong><br />
<textarea name="message" cols="30" rows="5"></textarea></p>
<p><input type="submit" value="send" /></p>
</form>
</body>
</html>
and the PHP
<html>
<head>
<title>Mail Sending Script</title>
</head>
<body>
<?php
echo "<p>Thank you, <b>".$_POST["name"]."</b>, for your message!</p>";
echo "<p>Your email address is: <b>".$_POST["email"]."</b>.</p>";
echo "<p>Your message was: <br/>";
echo $_POST["message"]."</p>";
//start building the mail string
$msg = "Name: ".$_POST["name"]."\n";
$msg .= "E-Mail: ".$_POST["email"]."\n";
$msg .= "Message: ".$_POST["message"]."\n";
//set up the mail
$recipient = "mailto#me.com";
$subject = "Form Submission Results";
$mailheaders = "From: My Web Site <defaultaddress#yourdomain.com> \n";
$mailheaders = "Reply-To: ".$_POST["email"];
//send the mail
mail($recipient, $subject, $msg, $mailheaders);
?>
</body>
</html>

If you use jQuery, as #Michael suggested, and which I also recommend, here is a great tutorial to do exactly that: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
In essence there are 3 parts:
1) HTML Form
2) Javascript/jQuery
Handles form submit event. You can do client side validations here, and if satisfied, submit the form via AJAX to your php script for processing.
3) PHP script
Handles server side processing of the form. Returns data back to your javascript so you can continue processing and do whatever you need to do from there.

This is where you need to start learning AJAX. Its purpose accomplishes exactly what you are doing. It stands for Asynchronous Javascript And XML.

You can go 2 ways:
1.) to look into some JavaScript, that does the job for you, most likely AJAX, via jQuery or Dojo or, if you are a masochist, by hand.
2.) Have an iframe somewhere in your page and make your form target be the iframe - this could be the part of the page carrying the form - so the biggest part of the page would stand still, while the form is replaced by the "thankyou" message.

You might wanna start getting into AJAX.
http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/
http://en.wikipedia.org/wiki/AJAX

You'd have to use jQuery. Something like this:
$("form").submit(function(event){
event.preventDefault();
var dataString = 'postVariableName=' + $("postVariableValue").val() + '&postVariableName=' + $("postVariableValue").val();
//alert (dataString);return false; //to check the string being sent
$.ajax({
type: "POST",
url: "postPath.php",
data: dataString,
success: function(data) {
//create jquery object from the response html
var $response=$(data);
//query the jq object for the values
var title = $response.filter('div#title').text(); //Check the resulting post page output for a div with an ID of "title", and put it's text into a variable called "title"
var cbody = $response.filter('div#cbody').html(); //Check the resulting post page output for a div with an ID of "cbody", and put it's html into a variable called "cbody"
$("input#title").val(title); //Display the title on the page
$("div#cbody").html(cbody); //Display the cbody on the page
}
});
});

Related

PHP Bypass jQuery Codes

I use this codes to save my contacts information into MySQL Database and apply JQuery Confirm Function for confirmation of data submitting, but when confirmation dialog open PHP Scripts can't stop, or Php bypass JQuery confirm codes and submit data into database, any idea regarding this issue.
<?php
//Database connection.
include'connect.php';
if(isset($_POST['name'])&&isset($_POST['email'])&&isset($_POST['contact'])){
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
if(empty($name)&&empty($email)&&empty($contact)){
echo'
<script>
$(document).ready(function(){
alert("Please fill all fields.");
});
</script>
';
}else{
if($sql = mysql_query("INSERT INTO contact_list VALUES ('', '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($contact)."')")){
echo'
<script>
$(document).ready(function(){
confirm("Are you sure to Saved Contact?");
});
</script>
';
}else{
echo'
<script>
$(document).ready(function(){
alert("Something is wrong, Please check");
});
</script>
';
}
}
}
?>
<html>
<form action="#" method="POST">
Full name:<input type="text" name="name">
Email:<input type="text" name="email">
Contact:<input type="text" name="contact">
</form>
</html>
PHP is executed by the server while javascript is executed by the client. And you want the server to "wait" or "stop execution" until some js code is executed by the client. Well, it's not possible.
You have to split your PHP code in two different PHP scripts: one for confirmation and one for data saving. For example, with pseudocode:
confirm.php
Hey, are you sure you want to save the data?
Yes, I'm sure
save.php
INSERT INTO 'blablabla' VALUES bla bla bla bla bla
Of course you don't really have to split it into two scripts. You can add one more $_POST parameter like "confirmed=true/false" and instead of two scripts just have one with one more if () {} else {} block.
But the idea is that you have to separate the two actions, cause you can't do both the confirmation and the saving at once with PHP.
There are also a few more options:
Use ajax to run the "saving script" once user confirms the operation
Use javascript to prevent the "saving script" from running without confirmation, something like: <input type="submit" onclick="return confirm('Sure?');" value="Save"/>

how do I get the message after submit to appear inside the pop up instead of on a different page

I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.

Using contenteditable in an email form using jQuery/Javascript

I've taken a few scripts from elsewhere on the Stack to create a contact form that emails me when the user submits.
HTML:
<form onsubmit="return getContent()">
<fieldset>
<input name="name" value="NAME" style="max-width:15%" type="text"/>
<input name="email" value="EMAIL" style="max-width: 30%" type="text"/>
<div id="message" contenteditable="true" name="message" value="expanding textarea">HELLO</div>
<textarea id="my-textarea" value="MESSAGE" style="display:none"></textarea>
<input type="submit" style="margin-right:0" value="Submit" />
</fieldset>
</form>
SCRIPTS:
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("message").innerHTML;
}
$('form').submit( function() {
$.ajax({
type: "POST",
url: "email.php",
data: $(this).serialize(),
success: function() {
// Update page with success message
}
});
return false;
});
PHP:
<?php
$recipient = "my.email#whatever.com"; //recipient
$Name = ($_POST['name']); //senders name
$email = ($_POST['email']); //senders e-mail adress
$mail_body = ($_POST['message']); //mail body
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields
mail($recipient, $subject, $mail_body, $header); //mail command :)
?>
The script SHOULD get the content entered in the contenteditable div and pass it through to the hidden textarea, then submit to my email. However, it's currently only passing through the "name" and "email" fields and leaving the body of the email blank.
What have I missed here?
EDIT: Made a small error in the code hidden textarea above, value="MESSAGE" not "SUBJECT". Still, code not working.
Contenteditable content doesn't get passed through the form when submitted.
But, it looks like you're using some JS to get the content of the editable content div and put it into the textarea with a name of "subject".
Therefore, it will be accessible through $_POST['subject'] only.
Also, you're doing an onsubmit="" in the html and a on submit in the JS file. I don't think both will work, you'd be better combining the two (i.e. just use the JS file).
It also won't work without JS enabled, which I'd say is a bigger problem.

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

PHP Contact Form - Want to stay on my site after send

I am in the process of creating a PHP contact form and all I have is that little problem, with the php script I have, that when the email was send out a new "Thank you" page is called.So the actual site with the contact form disappears BUT I DON`T WANT THAT HAPPEN.If the send button is hit I want to stay on my site, showing an empty contact form and maybe below the contact form just 1 line, saying "Thank you.....".How can I make that happen? Is there any code snippet out there that can explain to me what I have to include to my html and to my php file? Hopefully it will...Below is how my php ends right now.
// send Email
if (#mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader ))
{
// if email was successfully send
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
EDIT
#FreekOne
Currently I am using your code with a slight modification because I wanted to make the thank you and or error panel make slide out and have the text fade in. The script is accepting my code (because it is still working) but actually I can not see that the text actually fades in. I have seen samples of sliding panels with fading in text. So it seems to be a wrong kind of coding that I did.Please view the code here if you want: http://jsbin.com/ohuya3Maybe you can point me to the right direction. Of course, help would be appreciated from all of you guys here around.
Set the form to send the data to the same page, and have your script listen for a submit. Something like:
contact.php
<?php
// Check if form was previously submitted
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
$response = 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
<!-- HTML here -->
<?php
if (isset($response)) { // If a response was set, print it out
echo $response;
}
?>
<form method="POST" action="contact.php">
<!-- Your inputs go here -->
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<!-- More HTML here -->
UPDATE
Considering the provided extra info, I would personally do it with jQuery, through AJAX. First, setup your form and the container for the result:
HTML
<form id="myForm" method="POST" action="contact.php">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="text" id="message" name="message">
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<div id="formResponse" style="display: none;"></div>
Then setup the php script which handles the submitted data and outputs the response.
PHP (contact.php)
<?php
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
And finally, the jQuery script which will submit your form without leaving the page and insert the result in your result container (with a nice and simple fade in effect).
jQuery
$("#myForm").submit(function() {
$.post('contact.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'}, function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
Hope this helps !
All these answers below are wrong. It will make you occasionally spammed with doubled messages and confuse customers.
Though the solution is kinda tricky
First of all you have to learn the Golden rule:
After processing POST request, your code should redirect a browser using GET method. No exceptions.
Thus, first make it like this
if ($_SERVER['REQUEST METHOD']=='POST') {
mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// your form goes here
You ought to do it anyway.
Next, if you still want to show this useless message, you have several ways to do it.
using GET parameter
using cookie
ising AJAX.
for example, to use a GET parameter
if ($_SERVER['REQUEST_METHOD']=='POST') {
mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
header("Location: ".$_SERVER['PHP_SELF']."?thanks");
exit;
}
if ($_SERVER['QUERY_STRING']=='thanks') {
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
// your form goes here

Categories