Submitting a from with AJAX and mailing the submission - php

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

Related

How to get form input value? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm beginner for PHP. I have a form on the website and this form getting title and description values specific websites (with preg_match).
I want to add url input this form and when you add url and press submit button its auto get fields. Example
Frontend:
<input name="url">https://testdomain.com/posts/6412</input>
Backend:
$link = 'input values here';
Result:
Form fields (title and description getting) refresh or with ajax.
Create a Form and add the fields inside it..
In action, attribute add the file name where you want to post the form..
Form.php
<form method="POST" action="submit.php">
<input name="url" value="https://testdomain.com/posts/6412">
<input type="submit" name="submit" value="Submit">
</form>
submit.php
<?php
if(isset($_POST['submit'])){
$link = $_POST['url'];
}
?>
With AJAX
Form.php
<form method="POST" id="form" action="submit.php">
<div id="result"></div>
<input name="url" value="https://testdomain.com/posts/6412">
<input type="submit" name="submit" value="Submit">
</form>
<script>
$("#form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(response) {
$("#result").html(response);
}
});
});
</script>
submit.php
<?php
$link = $_POST['url'];
echo $link;
?>
for ajax, you must have to add jquery library before ajax code
If you use jQuery, you can use its serialize() method to get all the form inputs.
$("#form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(response) {
$("#result").html(response);
}
});
});
Note, however, that serialize() won't include the submit button itself. That's only submitted automatically in normal form submissions. If the server expects something like $_POST['submit'] to be set, you have to add it explicitly, e.g.
data: $(this).serialize() + '&submit=true',
Use this as your form, make sure to include method="post" in the form attribute section.
<form class="contact-form" method="post" action="processes/contactusform">
<div class="form-group">
<label for="name" class="sr-only">Name</label>
<input type="name" class="form-control" id="name" placeholder="Name" name="name" required />
</div>
<div class="form-group">
<label for="email" class="sr-only">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email" required />
</div>
<div class="form-group">
<label for="message" class="sr-only">Message</label>
<textarea class="form-control" id="message" rows="7" placeholder="Message" name="message" required /></textarea>
</div>
<div class="form-group">
<input type="submit" id="btn-submit" class="btn btn-send-message btn-md" value="Send Message" name="submit">
</div>
</form>
In your php code, you can refer to your inputs using:
$name = $_POST['name']; //you use 'name' because the value attribute in html for that specific input is set to "name"
$email = $_POST['email'];
$message = $_POST['message'];
Your welcome

data not being displayed correctly

When I submit a form using the attached code, instead of the message appearing in the div, the screen is refreshing itself and it is holding the completed form in the browser cache. I have obviously got it wrong somewhere and would be grateful if someone could point out my error. I have posted the relevant code, but if there is something I have missed, then please let me know.
In firebug, I can see the correct data that is being returned in the post tab.
I wasn't sure of the best place to post, so if this is incorrect, admin, please amend as you see fit. many thanks.
jquery code
//Begin function to submit report form
$(function(){
$(".frmreport").submit(function(){
var formdata = $(this).serialize();
$ajax({
type: "POST",
url: "../frm10010.php",
data: formdata,
dataType: "json",
success: function(msg){
$("#report_result").html("You have succesfully submitted your report. Thank you.");
}
});
return false;
});
});
// End function to submit report form
frm10010.php
<?php
$dept = mysql_real_escape_string($_POST['dept']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$position = mysql_real_escape_string($_POST['position']);
$feedback = mysql_real_escape_string($_POST['feedback']);
$form = array('dept'=>$dept, 'name'=>$name, 'email'=>$email, 'position'=>$position, 'feedback'=>$feedback);
$result = json_encode($form);
echo $result;
?>
html
<div id="report_result"></div>
<div id="formShow">
<form class=frmreport" method="post" class="webform">
<fieldset>
<legend><span class="subtitle">Submit Technical Report</span></legend>
<label for="dept">Department</label>
<input id="dept" name="dept" class="text" type="text" />
<label for="name">Full Name:</label>
<input id="name" name="name" class="text" type="text" />
<label for="email">Email address:</label>
<input id="email" name="email" class="text" type="text" />
<label for="position">Position:</label>
<input id="position" name="Position" class="text" type="text" />
<label for="feedback">Problem:</label>
<textarea name="feedback" cols="22" rows="5"></textarea>
</fieldset>
<input class="submit" type="submit" name="submit" value="Submit Report" />
<input class="cancel" type="reset" name="cancel" value="Clear Report" />
</form>
</div>
You have couple of errors here
$ajax({ should be $.ajax({
Second you have an error in the form class
<form class=frmreport" method="post" class="webform">
should be
<form class="frmreport" method="post" class="webform">
Don't use
$(".frmreport").submit(function(){
Instead use
$("#sub_btn").click(function(){
And in html
<input class="submit" type="submit" name="submit" value="Submit Report" />
Change it to
<input class="submit" id="sub_btn" type="button" name="submit" value="Submit Report" />
Another way to do it making submit handler false. But above solution will work here. There is also . is missing in ajax call.

Staying on page after submitting

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!"); }
);
}
}

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;
})
});

Search the database and load the returned query onto the page using jQuery and AJAX

I am doing some work on a page where I want to search the database based on what the user is looking for and then give back the results on the same page. I know how to make things disappear from a page using jQuery, but I would like to know how to append them to the page using AJAX.
The short of what I'm asking, I want to query the DB, and have the results pop up on the website without reloading the page.
Well the answer below is not really answering my question so I will give a more detailed question with an example.
<input type="textbox" id="name" name="name" />
<input type="button" id="search" name="search" value="Search the Database" /> <br/><br/>
<label class="userinfo">First Name: </label><input type="text" class="userinfo" id="first" name="first" /> <br/>
<label class="userinfo">Last Name: </label><input type="text" class="userinfo" id="last" name="last" /> <br/>
<label class="userinfo">Username: </label><input type="text" class="userinfo" id="uname" name="uname" /> <br/>
<label class="userinfo">E-Mail: </label><input type="text" class="userinfo" id="email" name="email" /> <br/>
<label class="userinfo">Admin Status: </label><input type="text" class="userinfo" id="admin" name="admin" /> <br/>
What happens is that I search the database based on the first textbox, the AJAX will happen when the search button is pressed, it will go to another page and do the query on the db. How do I get those results back to the original page to fill out the textboxes below? The texboxes below are hidden until the search button is clicked. So I need to send one variable and get multiple variables back. Does that help you help me more?
Here's a sample of ajax + html append:
<html>
<head>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
$.ajax({
type: "POST",
url: "process_thumbs.html",
data: "showposts=25",
success: function(html){
$("#output").html(html);
}
});
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
of course "process_thumbs.html" is a dynamic page returning the results of the query.

Categories