Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ajax in Wordpress to send mail

I'm trying to use Ajax to send an email through a web form I created, but I'm lost. I have no idea how Ajax functions in Wordpress.

I firstly created an action

add_action( 'wp_ajax_siteWideMessage', 'wpse_sendmail' );

The function that's supposed to retrieve the data and send the mail is:

function wpse_sendmail()
{
    $for = like_escape($_POST['forwhat']);
    $email = like_escape($_POST['email']);
    $headers = 'From: '.$email ."\r\n".'Reply-To: '.$email;
    $message = like_escape($_POST['message_message']);
    $respond = like_escape($_POST['message_email']);

    wp_mail( "[email protected]", "(OTN) Support: ".$support, $message, $headers); 
}

Finally, the js is like so:

$("#contact-send").click(function(){
    var forwhat = $("#contact-for").val();
    var name = $("#contact-name").val();
    var email = $("#contact-email").val();

    $.post( "<?php echo esc_js( site_url() ) ?>", { siteWideMessage:"null", forwhat: forwhat, name: name, email:email }, function(){
            console.log("success");
    });
});

I'm not too sure what I'm missing here. Can someone help me understand Wordpress's Ajax process?


UPDATE

I updated my code to this so far:

PHP

add_action( 'wp_ajax_siteWideMessage', 'wpse_sendmail' );
add_action( 'wp_ajax_nopriv_siteWideMessage', 'wpse_sendmail' );

function wpse_sendmail()
{
    $for = $_POST['forwhat'];
    $email = $_POST['email'];
    $headers = 'From: '.$email ."\r\n".'Reply-To: '.$email;
    $message = $_POST['message_message'];
    $respond = $_POST['message_email'];

    /*if(wp_mail( "[email protected]", "(OTN) Support: ".$for, $message, $headers))
    {
        echo "WOOHOO";
    }*/

    if($for)
    {
        //Just to see if there is any response.
        echo "Whoohoo";
    }

    die();
}

Js

$("#contact-send").click(function(){
    var forwhat = $("#contact-for").val();
    var name = $("#contact-name").val();
    var email = $("#contact-email").val();

    var data = { action:'siteWideMessage', forwhat:forwhat, name:name, email:email };
    $.post('<?php echo admin_url("admin-ajax.php"); ?>', data, function(response) {
        alert(response);
    });
});

Wordpress is still not responding with my AJAX command. I'm using the inspect element, and I see no data being passed around.

like image 331
Majo0od Avatar asked Oct 04 '14 01:10

Majo0od


People also ask

How do I upload a file using Ajax in WordPress?

Ajax File Upload in WordPress. For getting started, you need a form with the file input. We give an Ajax call on the selection of a file and upload the file to a server. To create a form, add the below HTML to your page template. Next, you have to give an Ajax call on the change event of file input.

What is Ajax submit Form in WordPress?

AJAX stands for Asynchronous JavaScript and XML. It uses JavaScript to send asynchronous request and handle the response from the server. So in this tutorial we are going to learn how to submit form using AJAX in WordPress.

How to perform Ajax operations in WordPress?

WordPress has a slightly different way to perform Ajax operations. In WordPress, we do give a call to the URL but the code we write to process the data will go in the function. Then this function needs to map with the ‘action’ value passed in Ajax parameters. Confused? Let’s see it in action.

How to add JS file in WordPress form?

Let’s first include the JS file in a WordPress environment. This code will go inside functions.php file or in a site-specific plugin. // Enqueued script with localized data. You are ready with the form and JS file.


2 Answers

At first you need to add two actions, one for the non-logged in user explicitly required to make it working, for example something like this (Basically in your functions.php file):

add_action( 'wp_ajax_siteWideMessage', 'wpse_sendmail' );
add_action( 'wp_ajax_nopriv_siteWideMessage', 'wpse_sendmail' );

Then, you need to make the request to the admin-ajax.php so in the jQuery function, you may use something like this:

$("#contact-send").click(function(e){

    e.preventDefault(); // if the clicked element is a link

    //...

    var data = { 'action':'siteWideMessage', 'more':'values' };

    $.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
        console.log(response);
    });

});

Make sure you put exit/die at the end of your handler in server side, for example:

function wpse_sendmail()
{
    // Process the post data...
    
    if(wp_mail(...)) {
        echo 'success';
    }
    else {
        echo 'failed';
    }

    die();
}

In your success callback, the response variable will get the response sent from the server side, i.e. success/failed. There are better ways to do this (Using wp_localize_script etc). Read this detailed article. Also, if you want to return a json response then you may use $.json('url', data, func).

If you are confused then let me tell you that, you should make the request to admin-ajax.php and pass the action with the request and in this case it is siteWideMessage, so WordPress will call the handler that's registered using add_action hook and in your case it's wpse_sendmail.Eid Mubarak :-)

like image 95
The Alpha Avatar answered Nov 04 '22 18:11

The Alpha


I had to do something slightly differently to get this to work.

First I added a hidden input on my template page and gave it the value of the ajax url like this:

<input type="hidden" id="ajax_url" value="<?php echo admin_url('admin-ajax.php'); ?>"/>

Then I had this in my functions.php

add_action( 'wp_ajax_siteWideMessage', 'wpse_sendmail' );
add_action( 'wp_ajax_nopriv_siteWideMessage', 'wpse_sendmail' );

function wpse_sendmail() {
  echo "hewwo world";

  die();
}

And my js in a seperate js file as such:

$("#submit-form").click(function(e){

  e.preventDefault(); // if the clicked element is a link

  $.post($("#ajax_url").val(), {
      action: 'siteWideMessage',
      // and the rest
  }, function(response) {
      // handle a successful response
      console.log(response)
  });

});

This works for me.

like image 28
Jack Robson Avatar answered Nov 04 '22 17:11

Jack Robson