Staying on page after submitting - php

just a question --
How do i actually submit a form and still stay on the same page whilst the script is being executed?
I have a simple form that goes like this:
<form action="process.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" id="name" required="required" />
<label for="email">Email</label>
<input type="email" name="email" id="email" required="required" />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" required="required" />
<label for="message">Message</label>
<input type="text" name="message" id="message" required="required" />
<input type="submit" id="button" value="Submit"/>
</form>
But everytime i submit the form it just goes to process.php. I don't want that, i want it to stay on the same page, maybe even have a jquery popup saying "thank you" or something.
How do i actually stay on the same page whilst the script is being run?

Put your form processing logic on the same page as the form
Use Ajax
Redirect back to that page when process.php is done processing the form

You have to use ajax in this case.
Basically, you need to post all data using ajax. In server side, you will need to get all parameters using $_POST['name'] like you normally do in server scripting.
FORM
<form action="process.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" id="name" required="required" />
<label for="email">Email</label>
<input type="email" name="email" id="email" required="required" />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" required="required" />
<label for="message">Message</label>
<input type="text" name="message" id="message" required="required" />
<input type="button" id="button" value="Submit"/>
</form>
<div id="dialog-message" title="Thank You">
<p>Your message here</p>
</div>
​
JQUERY
$(document).ready(function(){
$('#dialog-message').dialog({
modal: true,
autoOpen: false,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
$('#button').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
alert('');
$('#dialog-message').dialog('open');
}
});
});
});​
See the example here
Please note, dont forget to put jquery reference and also jquery ui reference

I think John Conde gave the best answer.
I would either make it so the php file that displays the form also handles the $_POST or if you can't do it that way then do it in Ajax with a code similar to this:
$("#form").bind("submit", function() {
var nameTxt = $("#name").val();
var emailTxt = $("#email").val();
$.post('process.php',
{
name: nameTxt,
email: emailTxt
},
function(data) {
if (data == 'ko')
alert('Could not submit...');
else {
alert('Thank you for your message.');
}
});
return false;
}
What this does is that it "blocks" the regular submit of the form when you click the submit button, retrieve input values and sends them to the process.php script.
It assumes that your "process.php" does an
echo "ko";
if there is an error. You can do some form cleanup after the form has been successfully sent by reseting the inputs:
$("#name").val('');
$("#email").val('');

Assuming you're using jquery:
$(document).ready(function(){
$('#form').submit(function(e){
// do some ajax request to process.php here...
// stop the form doing its default action of submitting directly to process.php
e.preventDefault();
});
});

try something like this
action="<?php print $_SERVER["PHP_SELF"]; ?>" (or) action=""
EDIT:
<?php
if(isset($_POST['Submit'])){
//do your validation or something here
header("location:Process.php");
}

I targeted an iframe to solve the problem, and it worked perfectly.
<form name="contact" role="form" method="post" action="contact.php" target="my_iframe">
Feild 1: <input name="feild1" id="feild1" type="text" placeholder="Lorem ipsum dolor"><br/><br/>
Feild 2: <input name="feild2" id="feild2" type="text" placeholder="Lorem ipsum dolor"><br/><br/>
Feild 3: <textarea name="feild3" id="feild3" rows="5" type="text" placeholder="Lorem ipsum dolor, sit amet."></textarea><br/><br/>
<input type="submit">
</form>
<!-- target iframe to prevent redirection to 'contact.php' -->
<iframe name="my_iframe" width="1" height="1" style="border:none"></iframe>

Literally:
<form action="process.php" method="post" id="form" target="_blank">
^^^^^^^^^^^^^^^^
This will make the browser stay on the same page, even if the form is submitted.
But you will be more likely looking for AJAX instead, some Introduction.

To do that you'll need jquery ajax, see here $.post

You can do something like this (with jQuery, untested)
$(function() {
$("#form").submit(e) {
// Prevent regular form submission
e.preventDefault();
// Submit the form via AJAX
var $form = $("#form");
$.post(
$form.attr("action"),
$form.serialize(),
function() { alert("Done!"); }
);
}
}

Related

Submitting form and posting to php script without reloading

I am trying to submit a form to a my PHP script that uses phpmailer to send emails. I am using a. ajax call to run the PHP script without refreshing but when I click the submit button all it does is refresh the page. Thank you.
Below is my form script
<form method="POST" name="form" onsubmit="return chk()">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button" onclick="return chk()"></p>
</fieldset>
</form>
Below is the ajax call. Its my first time using ajax so it may be wrong.
<script type="text/javascript">
function chk()
{
e.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var msg=document.getElementById('msg').value;
var dataString='name='+name+'&email='+email+'&msg='+msg;
$.ajax({
type:"post",
url:"mail.php",
data: dataString,
cache:false,
success: function(html) {
'Email Sent'
}
});
return false
}
</script>
To use .preventDefault() from a function you need to pass event as an argument
function chk(e){ //<<<<<<< here chk(e) while you're using e.preventDefault() if its somethingelse.preventDefault() so it should be chk(somethingelse)
e.preventDefault();
console.log('Not refreshed');
//return false; no need for it here.. return false here will work for a function not for the submit/click event so it will not prevent the default action in this case you've to use `preventDefault()`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="chk(event)"> <!-- ck(event) -->
<input type="submit" value="submit"> <!-- No need for onclick here -->
</form>
You can forget about the function and use the submit event directly .. no need to use onsubmit/onclick
$(document).ready(function(){
$("form[name='form']").on('submit' , function(e){
e.preventDefault();
console.log('Not refreshed');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" name="form">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button"></p>
</fieldset>
</form>

Submitting a from with AJAX and mailing the submission

So I have a contact form on my website. I was able to get the submission sent with perl and it works. But I don't want the page to refresh, instead, I want it to display a success message. To make it clearer, the form would look like this after it's submitted:
What I want it to look like after the submit button is clicked
Of course, I don't want the page to refresh.
I have tried several php tutorials and I read dozens of stackoverflow questions but I couldn't get it to work, maybe that's because am completely new to php and ajax. Help is greatly appreciated
That's the html of my form:
<form id="form" name='feedback' method='POST' action='/cgi-bin/TFmail.pl' accept-charset='UTF-8'>
<input type='hidden' name='_config' value='feedback' />
<div id="texts">
<input type="text" id="name" name="name" required placeholder="Full Name"/><br>
<input type="email" id="email" name="email" placeholder="E-mail" required/><br>
<input type="tel" id="phone" name="phone" placeholder="Phone Number" required/><br>
<textarea id="message" name="comments" placeholder="Type Message Here" required></textarea><br>
</div>
<div id="buttons">
<input id="but" type="submit" value="Submit"/>
<input id="clear" type="reset" value="Clear"/>
</div>
</form>
this is a basic form submission using ajax:
$("#form").submit(function(e) {
var url = "path-to-your-script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
taken from Submitting HTML form using Jquery AJAX

Textarea not sending on submit

Arg, this is so annoying!
I've got a form with a textarea. On submit I use a piece of php to send the data of the form to my email adress. The other data is sending fine (input) but it doesn't send the textarea along!
This is de PHP:
parse_str($_POST['stuff']);
mail("name#myemailadress.nl", "Website formulier", $name, $email, $comments);
This is the code:
<form class="form" id="form" action="" method="POST" >
<p class="name">
<input type="text" name="name" id="name" placeholder="NAAM" >
</p>
<p class="email">
<input type="text" name="email" id="email" placeholder="E-MAILADRES" >
</p>
<p class="text">
<textarea name="comments" id="bericht" placeholder="BERICHT" ></textarea>
</p>
<p class="submit">
<input type="submit" id="versturen_knop" class="submitBtn" value="VERSTUREN" >
</p>
</form>
This is the code that changes the state of the submit button for 3 seconds (message send confirmation) and triggers the PHP
$(document).ready(function(){
$('#form').submit(function(event){
$('.submitBtn').attr('value','BERICHT VERSTUURD!');
setTimeout(function(){
$('.submitBtn').attr('value','VERSTUREN');
}, 2000);
var stuff = $('#form').serialize();
jQuery.ajax({
type: 'POST',
url: 'mail.php',
data:{ 'stuff':stuff, }
});
//Prevents form submission
return false;
});
});
I hope you can help!
Try this instead
<?php
mail("name#myemailadress.nl", "Website formulier", $_POST['name'], $_POST['email'], $_POST['comments']);
?>
Try this code it works,
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form class="form" id="form" action="" method="POST" >
<p class="name">
<input type="text" name="name" id="name" placeholder="NAAM" >
</p>
<p class="email">
<input type="text" name="email" id="email" placeholder="E-MAILADRES" >
</p>
<p class="text">
<textarea name="comments" id="comments" placeholder="BERICHT" ></textarea>
</p>
<p class="submit">
<input type="submit" id="versturen_knop" class="submitBtn" value="VERSTUREN" >
</p>
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(event){
$('.submitBtn').attr('value','BERICHT VERSTUURD!');
setTimeout(function(){
$('.submitBtn').attr('value','VERSTUREN');
}, 2000);
//var stuff = $('#form').serialize();
jQuery.ajax({
type: 'POST',
url: 'mail.php',
data : $('#form').serialize(),
dataType: "json"
});
//Prevents form submission
return false;
});
});
</script>
<?php
parse_str($_POST['stuff']);
mail("aa#ss.com", "Website formulier", "$name, $email, $comments");
?>
You need to add entire contents in double quotes. I have tested it, it works fine.
Based on the circumstances, I suspect you are using a rich text editor like CKEdit or TinyMCE on your textarea.
If such is the case, you should know that these editors do not directly influence the textarea's text, and you must call a special editor-specific method to update it's contents. This method is called automatically on form submit, but for serializing and submitting forms via ajax it is not as straightforward.
If this is the case, please let me know which editor you are using and I can tell you how to correctly prepare the textarea for serialization.
Change following line
data : { 'stuff':stuff, }
to
data : stuff
or you can use
data : $('#form').serialize();
or you may try
data : {
'name' : $('#name').val(),
'email' : $('#email').val(),
'comments' : $('#bericht').val()
}
and retrieve using
$_POST['name']
$_POST['email']
$_POST['comments']

Form Cross domain POST request using PHP

I am trying to send data from a form to a php file so I can store it in a database, but its not working...
The code for the form is not on the same server as the php file, because the form will be on a mobile app.
html
<div data-role="page" id="createclub">
<div data-role="content">
<form id="cname" align="left" action="post">
<label for="name">Enter Name:</label>
<input type="text" id="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
<div id="result"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#cname").submit( function () {
$.post(
'http://www.clubbedin.isadcharity.org/createclub.php',
$("#cname").serialize(),
function(data){
$("#result").html(data);
alert("Data " + data);
}
);
return false;
});
});
</script>
php file
$name = $_POST['name'];
THANK YOU!!!
Add this at the beginning of your PHP file:
header("access-control-allow-origin: *");
More info on cross domain policy here.
I think you need to prevent the default function of the submit button using .preventDefault() because as I look on your code you want to submit your form using ajax
$("#cname").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.clubbedin.isadcharity.org/createclub.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#cname").serialize(),
success: function (data) {
$("#result").html(data);
alert("Data " + data);
},
});
});
and please use .ajax() so that you can set your ajax request to a cross-domain request
http://api.jquery.com/jQuery.ajax/
Your input element <input type="text" id="name" value="" /> must set up the name attribute as name="name".
form #cname after edited
<form id="cname" align="left" action="post">
<label for="name">Enter Name:</label>
<input type="text" id="name" name="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
You can gather more informations from the jQuery API Documention:
http://api.jquery.com/
http://api.jquery.com/serialize/

Sending an email via PHP and jquery/ajax from a html page

I have a very simple question but its been bugging me for quite some time .I have a html contact us page in which I have a simple form which already has validation assigned to it.The form code is :
<div class="contact_form">
<form method="post" id="contactForm" name="contactForm" action="">
<fieldset class="contactFieldset">
<ul>
<li>
<label for="contactName" class="leftLabel">*Name:</label>
<input type="text" name="contactName" id="contactName" class="contactInput required" value="" />
</li>
<p></p>
<li>
<label for="email" class="leftLabel">*Email:</label>
<input type="text" id="email" name="email" class="contactInput email required" value="" />
</li>
<span class="simple-success">I'll be in touch soon</span>
<li>
<label for="subject" class="leftLabel">*Subject:</label>
<input type="text" name="subject" id="subject" class="contactInput required" value="" />
</li>
<p></p>
<li>
<label for="message" class="leftLabel">*Message:</label>
<textarea rows="10" cols="40" id="message" name="message" class="contactTextarea required"></textarea>
</li>
<p></p>
<li>
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
</li>
</ul>
</fieldset>
</form>
</div>
The code which I am using to try and call the php form using ajax is this
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
alert("test i am here");
/*get the email value*/
var email = $("input#email").val();
var name = $("input#contactName").val();
var subject = $("input#subject").val();
var message=$("input#message").val();
alert("email"+email);
/* Check if the email is good or bad */
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
apos=email.indexOf("#");dotpos = email.lastIndexOf(".");lastpos=email.length-1;
var badEmail = (apos<1 || dotpos-apos<2 || lastpos-dotpos<2);
/*If the email is bad ,display the error message*/
if (email=="" || !goodEmail || badEmail) {
$("email").focus();
return false;
}
var dataString = 'email='+ email + '\n Name='+ name+ '\n Subject='+ subject+ '\n message='+ message;
alert (dataString);
$.ajax({
type: "POST",
url: "mai.php",
data: dataString,
//Do not cache the page
cache: false,
success: function(html) {
$('.simple-sucess').fadeIn(100).show();
$('.contact_form').fadeOut(100).hide();
$('.simple_error').fadeOut(100).hide();
}
});
return false;
});
});
The thing is the alert is not even being displayed when I press the submit button..what am I doing wrong here?
The validation code is
<script type="text/javascript">
jQuery(document).ready(function($){
$("#contactForm").validate();
});
First of all, use the submit event, not the submit button click event because the submit button is already wired up to do a normal submit. There may also be a bug, be sure to check your javascript console for errors. Either way...
What you probably really want to do is use the jQuery form plugin which will make your code a lot more simple.
Then your revised code would be as simple as:
$('#contactForm').ajaxForm(function() {
$('.simple-sucess').fadeIn(100).show();
$('.contact_form').fadeOut(100).hide();
$('.simple_error').fadeOut(100).hide()
});
In this case you would lose your email validation, but why reinvent the wheel, there are tons of validators out there that already have the bugs worked out etc.
the first thing is you are using :
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
in your form, and in jquery you are using .click() event,
if try to change
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
to :
<input type="button" alt="Submit button" name="submit" class="submit" id="submit">
then it will work perfectly with the .click() event
or the second option you have if you don't want to change the input type then use .submit() instead of .click()
OMG, so many code lines. A little suggestion: keep it simple enough to debug. A jsfiddle demo is recommended for better answers.
Here I post my solution for ajax forms, which works in basic browsers without javascript support.
html:
<form method="post" id="contactForm" action="somewhere">
Name: <input type="text" name="contactName" />
<br />
<input type="submit" value="Submit this form" />
</form>
javascript:
jQuery(function($){
$('#contactForm').submit(function(e){
e.preventDefault?e.preventDefault():false;
$.post(this.action,$(this).serialize(),function(text){
//callbacks
console.log(text);
});
return false;
})
});

Categories