Wordpress and Ajax form submission - php

I'm totally lost here. Can anyone check what is going wrong with the form I'm trying to create here? It should send data with Ajax in WP custom theme without storying anything in the DB.
The console gives me an error that "firstname is not defined", line 67 of jQuery - data:{name:firstname, email:email, message:comment,action:'validate_form'} , but truly, I believe it will be more than that.
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Please, leave a message!*" class="textarea" required></textarea>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="success-message val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
And some jQuery:
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
var ajaxUrl = "/wp-admin/admin-ajax.php";
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();
jQuery("html, body").animate({
scrollTop: jQuery(".val-error").offset().top
}, 700)
}
else {
jQuery.ajax({
url: ajaxUrl,
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
PHP in the functions.php file:
add_action('wp_ajax_myaction', 'my_action_callback');
add_action('wp_ajax_nopriv_myaction', 'my_action_callback');
function my_action_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}
UPDATE
Attached is the fresh version in codepen. PHP is down below.
https://codepen.io/anon/pen/RVWaJY
add_action('wp_ajax_myaction', 'validate_form_callback');
add_action('wp_ajax_nopriv_myaction', 'validate_form_callback');
function validate_form_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type:
text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}

Think it may just be this typo:
var name = jQuery(".firstname").val();
The variable passed to data
name:firstname,
Let me know if that solves your problem. If not, I will look again. : )

The first issue with the code you've posted, as you've already identified, is the error in the console.
You're creating a variable name (ln 4) and then trying to reference it as firstname (ln 19). You're doing the same thing in the PHP callback. The object in the AJAX request sets the value as name yet you're trying to retrieve it with firstname.
The same problem applies to comment. The best approach would be to pick a label and use it consistently. Mixing comment and message will only lead to confusion.
The second issue is with the action. Your JS code sets the action as validate_form but your callback fires on myaction.
JS Updates:
. . .
var firstname = jQuery( ".firstname" ).val();
var email = jQuery(".email").val();
var comment = jQuery(".textarea").val();
. . .
method:"POST",
data: {
firstname: firstname,
email: email,
comment: comment,
action: 'validate_form'
},
PHP Updates:
add_action( 'wp_ajax_validate_form', 'validate_form_callback' );
add_action( 'wp_ajax_nopriv_validate_form', 'validate_form_callback' );
function validate_form_callback() {

Hello your data parameter need to be instead like this, you have inverted the way is suppose to be writting, your variable should be on the right side and the name you are going to use to call it in the php code should be in the left side:
data:{firstname:name, email:email, comment:message, action:'validate_form'},
remember that your variable your are passing are:
var name = jQuery(".firstname").val(); var email = jQuery(".email").val(); var message = jQuery(".textarea").val();
and in your php you are going to call like this:
$name= trim($_POST["firstname"]); $email = trim($_POST["email"]); $comment = trim($_POST["comment"]);

Related

Sending email in PHP using AJAX

I am trying to send email in PHP using AJAX in a simple contact form. I have the following codes for a simple form, PHP code for submit button and AJAX script.
When I am trying to send email it is not sending any email and always firing the AJAX error msg. I am not very well in AJAX integration with PHP.
Below is my code
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
I would move the php part to another file:
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
And in another email.php
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
You must be stop the default flow of that form by using event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata. then you create a seperate page in php and do the mail process in that page and change the form action link to that page
In html
<form method="post" class="myform" action="mail.php">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).on('submit', '.myform', function(e){
e.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: new FormData($(".myform")[0]),
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
if (result.status == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
</script>
In php - mail.php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
if($send_email)
{
$response = ['status' => 'success'];
}
else
{
$response = ['status' => 'error'];
}
echo json_encode($response);
}
So, the top answer works, but as #Mithu said, for some reason it always says:
'Error Sending email!'
After 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 2-4 spaces in front of the word 'success' or 'error'.
So, all you need is to exclude these spaces, for that we need to change 'succes' to 'this is success' and 'error' to 'this is error'(just to make spare letters in the front) and then we need to divide this string to words and to extract the last word. It will always be 'success' or 'error' regardless how much spaces the script will add or how much letters it will remove accidentally. And also you need to make another if else statement in the PHP to check FALSE instead of TRUE.
Also I've added a few lines which check if the fields are filled or not. And if they are not filled then you get a message 'Please fill in the forms.'.
So here how it looks and works for me:
Importing jquery library (you need to place it into the header):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
HTML (you need to put it there where you want to have the contact form):
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
JS (you need to put it in the footer):
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
// if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
let d = result.split(" ");
let y = d.slice(-1)[0];
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
if (y == 'success'){
$('.output_message').text('Message Sent!');
}
else if (y == 'miss'){
$('.output_message').text('Please fill in all the fields above.');
}
else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
email.php (you need to create this file in the same folder where you have your index.php):
<?php
// here we check if all fields are filled.
$required = array('name', 'email', 'message');
$error = false;
foreach($required as $field) {
if (empty($_REQUEST[$field])) {
$error = true;
}
}
//if something is not filled(empty) and error is true
if ($error) {
echo 'this is miss';
}
// if everything is filled then we execute the mail function
else {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;
// Set your email address where you want to receive emails.
$to = 'contact#yourdomain.com';
$subject = 'Message from YOUR E-MAIL.COM';
$send_email = mail($to,$subject,$fullmessage,$email);
if ($send_email == false) {
echo 'this is error';
} else {
echo 'this is success';
}
}
?>
So,this code steadily works for me, but maybe it is not very proffessionaly made, because I am a begginer in JS and PHP.

Error in submit form with ajax and send mail in wordpress

I am trying submit custom form written in header.php with ajax and send mail to particular email address with submitted data,but getting error of 404 in console, form validation is performs taht means jquery file is loaded but when trying to call ajaxurl to send mail it gives 404 error. I am 100% sure that error is in ajax call or need to make function in function.php for sending mail but can't solve it out, can anyone help me solve out this issue?
Form in header.php
<form id="wp_con_form" method="post">
<ul class="form-list wp_contact_form_ul cf">
<li>
<input type="text" name="name" id="name" placeholder="Name *" class="text-field wp_con_frm_name">
</li>
<li>
<input type="text" name="phone" id="phone" placeholder="Phone *" class="text-field wp_con_frm_phone">
</li>
<li>
<input type="text" name="email" id="email" placeholder="Email *" class="text-field wp_con_frm_email">
</li>
<li>
<input type="text" name="agency" id="agency" placeholder="agency" class="text-field ">
</li>
<li class="full">
<textarea name="message" id="message" placeholder="Message *" class="text-field wp_con_frm_message"></textarea>
</li>
<li class="form-button">
<input type="submit" value="Send" id="wp_con_frm_btn" class="button" />
</li>
<div class="wp_cont_form_msg"></div>
</ul>
</form>
calling jquery file in function.php is
wp_enqueue_style( 'themestyle', get_template_directory_uri() . '/assets/css/style.css',false,'1.1','all' );
wp_localize_script("themestyle","the_ajax_theme", array("ajaxurl_anyName" => admin_url("admin-ajax.php")));
Jquery file for validation and ajax call
var j = jQuery.noConflict();
j(document).ready(function(){
function validateContact(){
var output = true;
j('.wp_contact_form_ul li').removeClass('wp_cont_frm_err_msg');
if(!(j(".wp_con_frm_name").val())){
j(".wp_con_frm_name").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_phone").val())){
j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!j(".wp_con_frm_phone").val().match(/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/))
{
j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_email").val())){
j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!j(".wp_con_frm_email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_message").val())){
j(".wp_con_frm_message").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
return output;
}
/* send contact form data to email */
function afterSubmit(getobj)
{
if(getobj.status)
{
j('#wp_con_form')[0].reset();
j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp();
}
else
{
j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp(5000);
}
}
j('#wp_con_frm_btn').click(function(){
var output = validateContact();
if(output){
var dataString = j("#wp_con_form").serialize();
j.ajax({
type: "POST",
url: ajaxurl,
dataType:"json",
data: dataString,
}).always(function(data)
{
afterSubmit(data);
});
}
return false;
});
});
code for sending mail in function.php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to = 'yourname#example.com';
$subject = 'List Qwick';
$message = 'Name: '.$name. "\r\n" .
'Phone: '.$phone. "\r\n" .
'Email: '.$email. "\r\n" .
'Message: '.$msg. "\r\n" .
$headers = "From: ".$email."\r\n" .'X-Mailer: PHP/' . phpversion();
if(wp_mail($to, $subject, $message, $headers))
{
$getMessage = '<p class="success">Your Email Has Been Sent Successfully</p>';
echo json_encode(array('status'=>1,'message'=>$getMessage));
}
else
{
$getMessage = '<p class="error">Mail function not working..</p>';
echo json_encode(array('status'=>0,'message'=>$getMessage));
}
When you make the Ajax URL available for JavaScript, you're actually creating an object called the_ajax_theme, and one of its properties is called ajaxurl_anyName and contains your Ajax URL.
wp_localize_script( 'themestyle', 'the_ajax_theme', array(
'ajaxurl_anyName' => admin_url( 'admin-ajax.php' )
) );
In your Ajax call, you're trying to access the ajaxurl which doesn't exists. To use the value that you're actually defining, you have to use the names you defined in your wp_localize_script(). So, your Ajax call should look like this:
j('#wp_con_frm_btn').click(function(){
var output = validateContact();
if(output){
var dataString = j("#wp_con_form").serialize();
j.ajax({
type: "POST",
url: the_ajax_theme.ajaxurl_anyName,
dataType:"json",
data: dataString,
}).always(function(data)
{
afterSubmit(data);
});
}
return false;
});
I'd recommend to use shorten names like themeSlug.ajaxURL.
It doesn't look like ajaxurl is ever set, so you're getting a 404 on an "undefined" URL. Set that value and you should be set.
It's possible it needs the admin-ajax.php file from WordPress, for the form action.
<form action="<?php echo admin_url( 'admin-ajax.php' ) ?>" method="post">
Also, it doesn't look like you're defining ajaxurl in your JavaScript. Try adding this:
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
Add it above or below this line in your existing code:
var dataString = j("#wp_con_form").serialize();

How to send an email using jQuery and POST

Update: Final working code is at the very bottom of question I left the rest of the code so you can see the process hope it helps someone in the future.
I am trying to send an email to myself (which is working) using only jQuery and an external php file, however, the email isn't picking up any of the data. I have the following code.
HTML
<section>
<form enctype="multipart/form-data">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" id="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input type="email" name="form_email" id="form_email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" id="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#form_message").val()
};
$.ajax({
type: "POST",
url: "email-php.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
PHP
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//send email
mail("email#domain.com", "From: " .$email, $message);
}
?>
EDIT: I took the above from various answers on Stack Overflow however couldn't figure out what I am missing or doing wrong. I took most of it from this question here jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined
UPDATE: After #inarilo's suggestion below I have changed everything to the following and now I don't get an email at all. This definitely looks like the better option so I would like to get it to work.
HTML
<section>
<form enctype="multipart/form-data" id="frmemail">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input type="email" name="form_email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
PHP
<?php
if(isset($_POST['name'],$_POST['email'],$_POST['message'])){
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
//send email
mail("landon#thecallfamily.com", "From: " .$email, $message);
}
?>
Final Working Code
HTML
<section>
<form enctype="multipart/form-data" id="frmemail">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input name="form_email" type="email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
$(document).ready(function() {
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: 'email-php.php',
data: $('#frmemail').serialize(),
success: function() {
$('.success').fadeIn(1000)
}
})
})
})
PHP
<?php
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
$to = "landon#thecallfamily.com";
$subject = "RIA Emails";
$body = "Name: ".$name."\nEmail: ".$email."\nMessage: ".$message;
$headers = "From: " . $email;
//send email
mail($to, $subject, $body, $headers);
?>
You have multiple errors, first of all you are using element ids to pick up the data:
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
but the input elements themselves have no id attribute defined.
Secondly, you are passing name, email and message, but in your PHP you are using name, email and text:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
However, even if correct all this is unnecessarily complicated, you can instead just serialize the form:
In the HTML, add an id to the form:
<form enctype="multipart/form-data" id="frmemail">
In JS, pick up the form and serialize it:
$(document).ready(function(){
$("#frmemail").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
});
});
And in PHP simply use the element names, you don't need ids for them:
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
you are trying to get textarea value by using wrong id, it should be:
message: $("#form_msg").val()
not
message: $("#form_email").val()
and in php file, replace the following:
$message = $_POST['text'];
with
$message = $_POST['message'];
that's it :)
try this, (supposed you have put id names on you input form)
JQUERY:
$(document).ready(function(){
$('#submit').on('click',function(){
var name = $('#name').val(),
var name = $('#email').val(),
var name = $('#message').val();
$.ajax({
type: "POST",
url: "email-php.php",
data: {name:name,email:email,message:message},
success: function(data){
alert(data);
}
});
});
});
PHP:
if(isset($_POST['name'],$_POST['email'],$_POST['message'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
echo $name; // then echo $email and then $message
}

Creating a contact form with Jquery/PHP that does not refresh

I'm a fairly new to web development. Mostly I'm a freelance artist trying to make her own web portfolio. Although I recognize the importance of learning the basics of code so I'm trying to do this all myself as I go.
Currently I'm at a stalemate with a simple PHP/HTML Contact Form. I have some forms on my HTML index (it's a one page site) that call in my PHP file to send the message to my email. As you probably would expect it looks a little something like this:
Index.html
<input name="name" type="text" placeholder="First and last name">
<input name="email" type="email" id="email" placeholder="Email address">
<textarea name="message" placeholder="Your Message"></textarea>
<input id="Submit" class="submit_btn" name="submit" type="submit" value="Submit">
</form>
Contactme.php
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: mywebsite.com';
$to = 'twocoffeespoons#gmail.com';
$subject = 'Hello';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
} else {
echo '<p>Something went wrong, go back and stry again!</p>';
}
}
?>
I think I understand the basics, but I'm really not satisfied with my form. When the user hits my submit button the php script is run and they are taken to a different page. I know I could simply change my website to index.php but I'd rather not. Even then the website still refreshes after I hit send. I've been looking through everything I can find, but the tutorials seem really outdated.
Does anybody have some advice? I'd like to use AJAX/JQuery to send the input to my php while the user just gets a "Your Message Has Been Sent Alert" without leaving my website. I'm sorry if my terminology is off or a little confusing. Like I said I'm really new to this, and have been trying to solve this problem for the last three days with no results.
try something like this
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
});
HTML CODE
<form id="ajaxform" action="your_url_goes_here">
.......
</form>
HTML
<input name="name" id="first" type="text" placeholder="First and last name">
<input name="email" type="email" id="email" placeholder="Email address">
<textarea id="message" name="message" placeholder="Your Message"></textarea>
<input id="Submit" class="submit_btn" name="submit" type="submit" value="Submit">
<span class="error" style="display:none">All Fields Are Required!</span>
<span class="success" style="display:none">Contact Form Submitted Successfully</span>
Script
$(function() {
$(".submit_btn").click(function() {
var name = $("#first").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email+ '&message' + message;
if (name == '' || email == '' || message == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "Contactme.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#formid").submit(function() {
// your code
return false; //return false also works..
});
- just try this code it will help you , submit your form as method="POST" and action="abc.php";
<?php
if(isset($_POST['submit'])){
$to=$_POST['email'];
$from=$_POST['name'];
$message=$_POST['message'];
$headers = "From:" . $from;
mail($to,$message,$headers);
echo "Mail Sent.";
}
?>

PHP mail function + ajax = frustrated me

I'm using ajax to submit a contact from without reloading the page, it works well for the most part except when I try to send the body of the message nothing gets sent. The to and subject parts work fine, it is just when the body tries to get sent I see nothing. I've tested it running strickly a php function and the body works, just the page reloads and I'm not sure why it works here, but not with ajax. If anybody could shed some light it'd be great, thanks.
.js
$(document).ready(function () {
$('#submit').click(function () {
var contactformdata = {
you: $('#you').val(),
subject: $('#subject').val(),
message: $('#contactbody').val(),
}
$.ajax({
url: "http://www.trenthauck.com/index.php/home/sendemail",
type: 'POST',
data: contactformdata,
success: function () {
$('#contactheader').replaceWith("<p class='header'>Thanks</p>");
$('#contactform').remove();
$('#contactlink').remove();
$(document).scrollTop(25);
}
});
return false;
});
});
Here is the php function (using CI, btw)
function sendemail(){
$to = "auck#gmail.com";
$from = $this->input->post('you');
$subject = $this->input->post('subject');
$message = $this->input->post('contactbody');
$tosend = "From: " . $from . "\nMessage: " . $message;
mail($to, $subject, $message);
$this->index();
}
And the form if that helps
<div class="divider" id="contact">
<p class = "header"><a id="contactheader" name="gocontact">Contact</a></p>
<div id = "contactform">
<form method = "post" id="contactform" action="<?php site_url()?>index.php/home/sendemail">
<div id ="formtitles">
<p class = "info">You:</p>
<p class = "info">Me:</p>
<p class = "info">Subject:</p>
<p class = "info">Body:</p>
<input id = "submit" type="submit" value="Send" />
</div>
<div id ="formfields">
<input id="you" type="text" name="you" /><br/>
<p class = "info">auck#gmail.com</p>
<input id ="subject" type="text" name="subject" /><br/>
<textarea id = "contactbody" name="contactbody"></textarea>
</div>
</form>
</div>
</div>
Thanks for the help
in the jquery you're sending the message using the variable 'message' but in the php you're picking it up using 'contactbody'.
change the php from:
$message = $this->input->post('contactbody');
to:
$message = $this->input->post('message');

Categories