2

This is my first Craft website, and after trying out Craft 2 I decided it would be a good idea to have move my site to Craft 3 for longevity.

I used to the free Contact Form plugin and managed to make AJAX work perfectly with Craft 2.

However the same code does not work with Craft 3.

I have a simple contact form at the bottom of https://haydentomas.co.uk where the AJAX works perfectly.

I used exactly the same code on a Craft 3 install at https://letsdocode.com. The error messages come up correctly if you don't fill in the form properly, and I do get an email if it does get filled in. But I cannot make the form success message appear when it has been completed successfully.

On the JS I have an success:

function(response) {
    if (response.success) {

Statement that holds some HTML that appears on an id and also another statement that hides the form completely.

This does not work and I am wondering if there is a change in Craft 3 that means I have to change the code slightly?

My else statement works perfectly.

My JS is below

   <script>
    $('form').submit(function(ev) {
      // Prevent the form from actually submitting
      ev.preventDefault();
      var formData = new FormData($(this)[0]);
      // Send it to the server
      $.ajax('/', {    
        url:  '/',
        data: formData,
        type: 'POST',
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(response) {
        if (response.success) {
          document.getElementById("notice").innerHTML = '<h2>Success!</h2><div class="row"><div class="6u"><img class="monkey" src="https://haydentomas.co.uk//images/monkey.svg"/> </div><div class="6u"><p>Thank you for your message</p><p>I will get back to you as soon as possible, usually within 24 hours</p><p>Talk soon! Hayden</p></div></div>';
          // $('form')[0].reset();
          document.getElementById("form").style.display = "none";
        } else {
            // response.error will be an object containing any validation errors that occurred, indexed by field name
            // e.g. response.error.fromName => ['From Name is required']
            document.getElementsByName('fromName')[0].placeholder='Name is required';
            document.getElementsByName('fromEmail')[0].placeholder='Email is required';
            document.getElementsByName('message')[0].placeholder='Message is required';
            }
          }
          });
      });
</script>

My form is

<div id="form">
    <form method="post" action="" accept-charset="UTF-8">
        <input type="hidden" name="CRAFT_CSRF_TOKEN" value="p_O1wR-QVP9G9WpcPZ90Fl4K82X8kOvZ33FAXa7fej9HSTOMW4zC_GWWsVDAVlvkr_TjeheMVdsk15JD5C8D-CSrFP0Ehb9kCoyHF42u_37Myy_akFOwXWJprfT4KWOqpzUhWd6r0ib9QLr7G2cDBUtxDH9JgIF3alyLyHuZhZXAO_eR79zoCVniIzlieZZi0FOsLQhYQxSpOVuzLDdFAg7P2U7zQBUXSJ1dnNXapMuyTUjLcuu3sJNFLzwozOcOGqo1K9kGRSTxXU2_bF4FctCHwoxe-gXSCLBcBRDzN1s9S7c9yNWZ6etHMC_7qxNXf31luALE9sgZ9dcy92c6gJaS2xggume9EOKnd4dLNMkRmiTEZeaIXTLvsXG5yplOqvNJ6aVhhW5XXpmRzh1ayJNXFGm7zuRHxDfOjFYmaVRmP0lJEK3tNCc_yowjrcDn8A_B4Z2JnGAx2hdvViDeVuQvnVEsajowmAp__gJ_FlRrm7gPlCRyYTzJLtSTls2fnDkCoB7b-9v6FURVfpmjRSyZfGqWVgRDpBV0xVo9dRc=">
        <input type="hidden" name="action" value="contact-form/send">
        <input type="hidden" name="redirect" value="b72e5e9e85a0ff7d840441aa540d6d32c6d554d22c025c8fc4dc8e0804c9475fcontact/thanks">

        <h3><label for="from-name">Your Name</label></h3>
        <input id="from-name" type="text" name="fromName" value="">

        <h3><label for="from-email">Your Email</label></h3>
        <input id="from-email" type="email" name="fromEmail" value="">

        <h3><label for="subject">Subject</label></h3>
        <input id="subject" type="text" name="subject" value="">

        <h3><label for="message">Message</label></h3>
        <textarea rows="10" cols="40" id="message" name="message"></textarea>

        <input type="submit" value="Send">
    </form>
</div>

Thanks in advance!

3
  • We need your html in order to help you. Your Javascript seems to be "correct". I know one could inspect it on your website but people on smartphones might help you too when you post it May 5 '18 at 21:40
  • Ok, thanks. I have added the form to the post. I am pretty sure the form should work, as it does on craft2, so must be a different success message, or I have missed something! May 5 '18 at 21:52
  • As far as I can see you don't close your </form> and there is no div with id notice the response message from the controller still contains an attribute success. You can do console.log(response) to see what you get May 5 '18 at 21:54
1

Contact Form 2 (for Craft 3), still returns a JSON encoded success: true response on successful submission, but Craft 3 by default will only respond with JSON if $request->getAcceptsJson() returns true on a request.

https://github.com/craftcms/contact-form/blob/v2/src/controllers/SendController.php#L64-L66

Ultimately that ends up hitting the Yii 2 method getAcceptableContentTypes which checks the $_SERVER['HTTP_ACCEPT'] server variable for the key application/json.

So most likely your server is not configured to return application/json as a valid HTTP_ACCEPT content-type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.