I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...
So anybody who wants can send a tip of the ad to some friends email-adress.
I am guessing the form must be submitted to a php page right?
<form name="tip" method="post" action="tip.php">
Tip somebody:
<input
name="tip_email"
type="text"
size="30"
onfocus="tip_div(1);"
onblur="tip_div(2);"
/>
<input type="submit" value="Skicka Tips" />
<input type="hidden" name="ad_id" />
</form>
When submitting the form, the page gets reloaded... I don't want that...
Is there any way to make it not reload and still send the mail?
Preferrably without ajax or jquery...
I've found what I think is an easier way.
If you put an Iframe in the page, you can redirect the exit of the action there and make it show up.
You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/
Your code should be something along the lines of:
$('#submit').click(function() {
$.ajax({
url: 'send_email.php',
type: 'POST',
data: {
email: 'email#example.com',
message: 'hello world!'
},
success: function(msg) {
alert('Email Sent');
}
});
});
The form will submit in the background to the send_email.php page which will need to handle the request and send the email.
You either use AJAX or you
create and append an iframe to the document
set the iframes name to 'foo'
set the forms target to 'foo'
submit
have the forms action render javascript with 'parent.notify(...)' to give feedback
optionally you can remove the iframe
Fastest and easiest way is to use an iframe.
Put a frame at the bottom of your page.
<iframe name="frame"></iframe>
And in your form do this.
<form target="frame">
</form>
and to make the frame invisible in your css.
iframe{
display: none;
}
SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.
Here's some of the code I found on the internet that solves this problem :
1.) IFRAME
When the form is submitted, The action will be executed and target the specific iframe to reload.
index.php
<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>
iframe_content.php
<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
echo $Name;
}
?>
2.) AJAX
Index.php:
<form >
<input type="" name="name" id="name">
<input type="" name="descr" id="descr">
<input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
var descr=document.getElementById('descr').value;
$.ajax({
type:"post",
url:"server_action.php",
data:
{
'name' :name,
'descr' :descr
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
server_action.php
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';
echo $name;
echo $descr;
?>
Tags: phpajaxjqueryserversidehtml
A further possibility is to make a direct javascript link to your function:
<form action="javascript:your_function();" method="post">
...
It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.
First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().
event.preventDefault()
Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.
Example:
Form:
<form id="form-id" onsubmit="func()">
<input id="input-id" type="text">
</form>
Javascript:
function func(){
event.preventDefault();
var newValue = $('#input-field-id').val();
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
}
this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:
<select name="aAddToPage[65654]"
onchange="
if (bCanAddMore) {
addToPage(65654,this);
}
else {
alert('Could not add another, wait until previous is added.');
this.options[0].selected = true;
};
" />
<option value="">Add to page..</option>
[more options with values here]</select>
<script type="text/javascript">
function addToPage(iProduct, oSelect){
iPage = oSelect.options[oSelect.selectedIndex].value;
if (iPage != "") {
bCanAddMore = false;
window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
window.hiddenFrame.document.formFrame.submit();
}
}
var bCanAddMore = true;</script>
<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>
the php code generating the page that is being called above:
if( $_GET['p'] == 'addProductToPage' ){ // hidden form processing
if(!empty($_POST['iAddToPage'])) {
//.. do something with it..
}
print('
<html>
<body>
<form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
<input type="hidden" name="iProduct" value="" />
<input type="hidden" name="iAddToPage" value="" />
</form>
</body>
</html>
');
}
This should solve your problem.In this code after submit button click we call jquery ajax and we pass url to posttype POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.
<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
<input type="submit" id="submit" value="Skicka Tips"/>
<input type="hidden" id="ad_id" name="ad_id" />
</form>
<script>
$( "#tip" ).submit(function( e ) {
e.preventDefault();
$.ajax({
url: tip.php,
type:'POST',
data:
{
tip_email: $('#tip_email').val(),
ad_id: $('#ad_id').val()
},
success: function(msg)
{
alert('Email Sent');
}
});
});
</script>
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
Have you tried using an iFrame? No ajax, and the original page will not load.
You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.
function Foo(){
event.preventDefault();
$.ajax( {
url:"<?php echo base_url();?>Controllername/ctlr_function",
type:"POST",
data:'email='+$("#email").val(),
success:function(msg) {
alert('You are subscribed');
}
} );
}
I tried many times for a good solution and answer by #taufique helped me to arrive at this answer.
NB : Don't forget to put event.preventDefault(); at the beginning of the body of the function .
I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases.
So here is what I came up with:
<script>
$(document).ready(function(){
$("#text_only_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
});
$("#pic_radio_button_id").click(function(){
$("#single_pic_div").show();
$("#multi_pic_div").hide();
});
$("#gallery_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").show();
});
$("#my_Submit_button_ID").click(function() {
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
var canvas=document.getElementById("canvas");
var canvasA=document.getElementById("canvasA");
var canvasB=document.getElementById("canvasB");
var canvasC=document.getElementById("canvasC");
var canvasD=document.getElementById("canvasD");
var ctx=canvas.getContext("2d");
var ctxA=canvasA.getContext("2d");
var ctxB=canvasB.getContext("2d");
var ctxC=canvasC.getContext("2d");
var ctxD=canvasD.getContext("2d");
ctx.clearRect(0, 0,480,480);
ctxA.clearRect(0, 0,480,480);
ctxB.clearRect(0, 0,480,480);
ctxC.clearRect(0, 0,480,480);
ctxD.clearRect(0, 0,480,480);
} });
return false;
}); });
</script>
That works well for me, for your application of just an html form, we can simplify this jquery code like this:
<script>
$(document).ready(function(){
$("#my_Submit_button_ID").click(function() {
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
} });
return false;
}); });
</script>
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
Create inedx.php and insert:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
If everything is ok, change the code on email.php to:
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: test#test.com \r\n";
$headers .= "Reply-To: test#test.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
Modern Answer without XHR or jQuery
It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!
The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault():
form.addEventListener("submit", function(event){
event.preventDefault();
// ...
});
Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData object, populating it with the form's values, and use it as the body of a fetch request:
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Note that this submits an HTTP request using the multipart/form-data format. If you need to post the data using application/x-www-form-urlencoded, create a new URLSearchParams object from the FormData object and use that as the fetch's body.
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Here's a full code example:
let form = document.querySelector("form");
form.addEventListener("submit", function(event){
event.preventDefault();
fetch(form.action, {
method: "post",
body: //new FormData(form) // for multipart/form-data
new URLSearchParams(new FormData(form)) //for application/x-www-form-urlencoded
});
});
<form method="POST">
<input name="name" placeholder="Name" />
<input name="phone" type="tel" placeholder="Phone" />
<input name="email" type="email" placeholder="Email" />
<input name="submit" type="submit" />
</form>
The page will get reloaded if you don't want to use javascript
You will need to use JavaScript without resulting to an iframe (ugly approach).
You can do it in JavaScript; using jQuery will make it painless.
I suggest you check out AJAX and Posting.
if you're submitting to the same page where the form is you could write the form tags with out an action and it will submit, like this
<form method='post'> <!-- you can see there is no action here-->
Here is some jQuery for posting to a php page and getting html back:
$('form').submit(function() {
$.post('tip.php', function(html) {
// do what you need in your success callback
}
return false;
});
first of all, I know this topic has been discussed in the past but I didn't manage to come to a conclusion, so any help is VERY appreciated.
I know a bit of html but I'm not a programmer, I had someone building a website for me but the web form is often sending duplicate (even 3 or 4 times) emails. I believe (assume) it has to do with people refreshing or hitting the submit button more than once. I tried to disable the 'submit' but I didn't manage to.
At this stage any fix would help. As long as I stop receiving multiple emails from senders.
I will try giving you as much information as possible.
This is the html code for the form:
<div class="form-input">
<div class="form-title">NAME</div>
<input id="form-name" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">EMAIL</div>
<input id="form-email" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">MESSAGE</div>
<textarea id="form-msg" type="text"></textarea>
</div>
<div class="form-input">
<div class="form-title"> </div>
<input id="form-send" type="submit" value="SEND"></input>
</div>
</div><!--end of form holder-->
<div id="details-error">Please comlete all fields and include a valid email</div>
<div id="form-sent">Thankyou for your enquiry - We will be in touch shortly!</div>
</div>
</div>
</div>
</div>
the following is the script I have:
// Contact Form Code
$('#form-send').click(function(){
var name = $('#form-name').val();
var email = $('#form-email').val();
var message = $('#form-msg').val();
var option = $('#form-select').val();
var error = 0;
if(name === '' || email === '' || message === ''){
error = 1;
$('#details-error').fadeIn(200);
}else{
$('#details-error').fadeOut(200);
}
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(email))) {
$('#details-error').fadeIn(200);
error = 1;
}
var dataString = '&option=' + option +'&name=' + name + '&email=' + email + '&text=' + message;
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
return false;
}
});
});
And lastly, the mail.php:
<?php
if ($_POST) {
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$option = $_POST['option'];
$headers = $option . "\r\n" . $name . "\r\n" . $email;
//send email
mail("xxx#email.net", "Mail Enquiry", $text, $headers);
}
?>
If the submit button is being pressed more than once then this may work.
Try adding the following line of code right after $('#form-send').click(function(){
$('#form-send').attr('disabled', 'disabled');
This will disable the submit button after it has been clicked once. If the page is reloaded by the user, it will be enabled.
Note: this code has not been tested.
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
This portion of code in #form-send click function is what to do when the submission was successful, you could modify the submit button to disable further clicks if you feel the users are clicking submit after they already submitted the form.
$('#form-send').attr('disabled','disabled'); // only disable the #form-send and not other forms that may need to still be submitted.
You should change the input to a button:
<input id="form-send" type="submit" value="SEND"></input>
to
<button id="form-send" type="button">SEND</button>
Because otherwise the form will be submitted once through ajax and then again via the form submit/page refresh
I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?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 id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<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 class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});
I have a success message that is displayed no matter if the user data is valid or not. I have an error message but I'm having trouble getting it to display. I'm not the best coder so be nice :)
Also, for some reason when I receive an email via the form the user's email comes up as user#MISSING_DOMAIN. My first issue takes priority, so you don't have to help me with this one if its too much.
Form Code
<form action="contactformprocess3.php" method="post" class="myForm" >
<input name="name" type="text" id="f1" class="name-textinput"/><br />
<script type="text/javascript">
var f1 = new LiveValidation('f1');
f1.add( Validate.Presence );
</script>
<input name="email" type="text" id="f21" class="email-textinput"/><br />
<script type="text/javascript">
var f21 = new LiveValidation('f21');
f21.add( Validate.Presence );
f21.add( Validate.Email );
f21.add( Validate.Length, { minimum: 10, maximum: 35 } );
</script>
<textarea name="message" rows="9" cols="34" id="field3" class="message-textinput"></textarea>
<span class="underform">
<input type="reset" class="reset" />
<input type="submit" value="submit" class="submit" />
</span>
</form>
AJAX
$(function() {
$('.myForm').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$('.success-box').fadeIn("slow").delay(3000).fadeOut("slow");
},
error: function(xhr, status, error, req) {
$('.failure-box').fadein("slow").delay(3000).fadeOut("slow");
}
});
});
});
PHP EMAIL
<?php
$to = 'wj#pieceofmedesigns.com';
$subject = 'Piece of Me Designs';
$from = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
if (mail($to, $subject, $message, 'From: '.$name.' <'.$from.'>')) {
echo 'Message was sent successfully.';
} else {
echo 'There was a problem sending your message.';
}
?>
What said Ed is totally correct. It means that you are waiting in the "error:" part of the ajax block what is for you a business rule disfunction (email not sent), while only technical errors will show up in this block.
A business error still returns "success" regarding to the technical point of view; it is just a different "success" answer that your application has to handle.
So, basically for you the solution is to check the echo:
success: function(msg) {
if (msg == 'Message was sent successfully.') {
$('.success-box').fadeIn("slow").delay(3000).fadeOut("slow");
} else {
$('.failure-box').fadein("slow").delay(3000).fadeOut("slow");
}
},
error: function(xhr, status, error, req) {
//alert the user there was a technical problem
}
I may recommend you return XML based echos from your php services, then you could manage tags and normalized responses way easier.
The AJAX error condition occurs when it is not possible to either contact the server or the server returns a status code that is not 200. Such things are file not found, script errors or network problems,
So to get the correct message you need to validate the data. You can do this before using AJAX to ensure that the data you send to the servers script has been validated.
Also you need to get your PHP script to do validation. This is a good policy to ensure security.
I'm trying to stay on the current page from where a form gets submitted. But somehow it's not working. I found some peaces of code on the internet and put it together.
This is the process.php file:
<?php
// Get Data
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$phone = strip_tags($_POST['phone']);
$subject = strip_tags($_POST['subject']);
$message = strip_tags($_POST['message']);
// Send Message
mail( "email#domain.com", "Contact Form testttt",
"Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $url\nMessage: $message\n",
"From: Forms testtttttttt" );
?>
And the rest of the code, the html and javascripts can be found on jsfiddle:
jsfiddled code
$(function(){
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'process.php',
success: function() {
$('#contact').hide();
$('#contact-form').append("<p class='thanks'>thanks test.</p>")
}
});
}
});
});
Forgot to mention what happens now. I get redirected to process.php page.
Use jQuery.ajax() function to submit a form without refreshing a page. You need to do something like this:
test.php:
<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript" src="ajaxform.js"></script>
<form action='process.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
process.php:
<?php
// Get your form data here in $_POST
?>
ajaxform.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Form is successfully submitted');
},
error : function(){
alert('Something wrong');
}
});
return false;
});
});
You need to either return a 204 HTTP status or make the request using JavaScript instead of by submitting the form (this is known as Ajax and there are numerous tutorials on the subject linked from the jQuery tutorials page).
This is a link to get you started :
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/