0

I am building a custom theme, and on my contact page, I want to send an email using AJAX. By doing some research, I have found a way to accomplish this.

Firstly, on submission of the form, I do some validations using regular javascript:

const contactFormSubmit = () => {
    const submitButton = document.querySelector('#contact-submit');
    console.log(submitButton);
    document.addEventListener('click', e => {
      if (e.target == submitButton) {
        e.preventDefault();
        const name = document.getElementById('name').value;
        const email = document.getElementById('email').value;
        const message = document.getElementById('message').value;
        checkForm(name, email, message);
      }
    })
  }

this code simply prevets default and grabs the input data. then we send the data to the checkForm() function to check for any errors.

const checkForm = (name, email, message) => {
    if (name && message && email) {
      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {

        jQuery.ajax({
           url: `<?php echo admin_url('admin-ajax.php'); ?>`,
           type: "POST",
           cache: false,
           data:{
              action: 'send_email',
              name: name,
              email: email,
              message: message,
                },
           success:function(res){
                   alert("Email Sent.");
                  }
        });

    printMessage('success', 'Thank you for you email. We will get back to you as soon as we can');
  } else {

    printMessage('error', 'email is not in the correct form')
  }
} else {
  printMessage('error', 'Make Sure all fields are filled out')
  }
 }

if there are errors, it will error out the message by sending it to printMessage.

const printMessage= (outcome, message) => {
    if (!messageOn) {
      resultMessageContainer = document.createElement('div');
      pageContent = document.querySelector('.contact-container');
      document.body.insertBefore(resultMessageContainer, pageContent);
    } else {
      resultMessageContainer.innerHTML = '';
    }

    if (outcome == 'success') {
      resultMessageContainer.innerHTML = `${outcome} ${message}`;
      console.log('SUCCESS');
      messageOn = true;
    } else if (outcome == 'error') {
      resultMessageContainer.innerHTML = `${outcome} ${message}`;
      console.log('failure');
      messageOn = true;
    }
  }

If there are no errors, we should make the ajax request to the back-end. However. in sending this ajax request, I am getting the following error:

jquery.min.js:4 POST http://elbe.local/contact-us/%3C?php%20echo%20admin_url(%27admin-ajax.php%27);%20?%3E 404 (Not Found)

from the error, I can tell that the problem is with the admin-ajax.php file. My javascript file is in a separate file, maybe that has something to do with it.

in my functions.php, this is the function taking care of sending the email.

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.<br>".
    "Name: $name. <br>".
    "Email: $email. <br>".
    "Message: $message. <br>";
      $to = "naderabouezze93@gmail.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";
        }
die();

}

any guidance as to how to make this work would be really appreciated. Thank you!

Nader
  • 67
  • 9
  • Where is `const checkForm` defined? In a JavaScript file? – Zoe Edwards Nov 16 '18 at 16:56
  • 1
    Why reinvent the wheel? There are some great free and premium form plugins that do all the hard work for you and they tend to be extensible for when you have special requirements. – Difster Nov 16 '18 at 16:58
  • @ThomasEdwards checkForm is a function I wrote to do the validations – Nader Nov 16 '18 at 17:12
  • @Difster I want to have something a little bit lighter than a plugin – Nader Nov 16 '18 at 17:17
  • Judging by your console output, `` is not being executed by the PHP engine. instead it's being output as-is. Is this code inside a .js file instead of a PHP file, by any chance? PHP is only executed inside .php files – ADyson Nov 16 '18 at 17:32
  • @ADyson yes it is in a .js file because it is an AJAX REQUEST! – Nader Nov 16 '18 at 17:37
  • Javascript (and thus AJAX code) can be written anywhere, either in a separate js file or in a ` – ADyson Nov 16 '18 at 17:48
  • So your options are either 1) move this JS code into a .php file somewhere, or 2) change the checkForm function so it accepts the URL as an input parameter, and then make sure that the code which calls this function is located in a .PHP script, and can provide the URL (injected from the PHP) to the external function. – ADyson Nov 16 '18 at 17:51

1 Answers1

0

As mentioned by @ADyson if this in .js file then PHP code is not executed, So you should get it through hidden input, like:

<input type="hidden" value="<?= admin_url('admin-ajax.php'); ?>" name=ajaxURL >

Include above code in PHP file, may be in header.php or footer.php

Then you can fetch like this:

url: jQuery('input[name=ajaxURL]').val(),

Wajid
  • 26
  • 1
  • 1
  • 8
  • well that's one way to inject it, but you'l need to go a little further and demonstrate how to actually use that value in the existing Javascript code. I'd argue though that you can still just inject it into some JavaScript as a literal, which is less verbose than having to read it from a hidden field. Only difference is, that bit of JavaScript must be generated from within a PHP script, not hard-coded into a separate file. – ADyson Nov 16 '18 at 17:52
  • @ADyson Yes you are right, this is just one way of doing this. And if this can be called from a PHP file then no need for above extra code. – Wajid Nov 16 '18 at 18:01
  • I have added the JS code to footer.php. it does seem to work now, although I am not receiving the email. I am recieving success alert! any reason as to why the email isnt actually sending? – Nader Nov 16 '18 at 18:04
  • May be SMTP issue. First thing is to send a test email with any plugin or your own code. This is a simple plugin to test email functionality. [Check-Email](https://wordpress.org/plugins/check-email/) – Wajid Nov 16 '18 at 18:14
  • @Wajid the test emails are not being delivered. Could this have to do with the fact that I am not online yet (currently using a local server)? I am sending the email from a local server. Or could this have to do with gmail not receiving it? – Nader Nov 16 '18 at 18:54
  • There is configuration issue on local server If your are using XAMPP. [Follow this link to configure].(https://stackoverflow.com/questions/15965376/how-to-configure-xampp-to-send-mail-from-localhost) – Wajid Nov 16 '18 at 20:19