How to send an email using ajax in Wordpress?

email.jpg
Here we will learn how to use ajax in the wordpreee, How to send an email using Ajax that means without refreshing a page we will send an email. I am showing you an easy way for all this. Suppose we have a form. Below i m showing you the simple bootstrap used form. We have three fields in this form that are Name, email and Message. And a submit button to send an email.

Please Fill This Form For Instant Access

And we have footer.php file to use the jquery ajax to get values. You can also use the jquery in the another js file. I am using in the footer.php file


In the above code the values are retrieve from the id of the each text boxes. and you will see the send_email action: 'send_email'is our function name which will we use in the function.php file to send an email using the above retrieved values. Functions.php

add_action( 'wp_ajax_send_email', 'callback_send_email' );
add_action( 'wp_ajax_nopriv_send_email', 'callback_send_email' );

function callback_send_email(){

	  $name = $_REQUEST['name'];
	  $email = $_REQUEST['email'];
          $message= $_REQUEST['message'];
          $subject = "Contact Form";
	  $email_body = "The following prospectus has contacted you.
". "Name: $name.
". "Email: $email.
". "Message: $message.
"; $to = "example@email.com"; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= "From: $name <$email> \r\n"; $headers .= "Reply-To: $email \r\n"; $mail = mail($to,$subject,$email_body,$headers); if($mail){ echo "Email Sent Successfully"; } }
By using above code. you will successfully send an email. change your email id with $to = "example@email.com"; your email id. That's it..