0

I have a page-contact.php for my contact form in my template. I wanted to add jquery validation and some fancy ajax action to my form. This is already a working code in a simple PHP page, but getting it work in wordpress fails.

My contact form:

<form id="contact_form" method="POST" action="" enctype="application/x-www-form-urlencoded" novalidate="novalidate">
    <input type="text" name="name" maxlength="30" id="name" placeholder="Your name">
    <input type="text" name="email" maxlength="30" id="email" placeholder="Your email">
    <textarea rows="2" cols="40" name="message" id="message" placeholder="Your message"></textarea>
    <input type="text" id="phone" name="phone" size="15" placeholder="Please do not fill your phone number">
    <input type="submit" id="click" class="button" value="Submit">
    <div id="loading_icon"><img src="/wp-content/themes/owlish/img/loading.gif" alt="loading"></div>
    <div id="response"></div>
</form>

the ajax function in functions.php

add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
    function sendmail() {
        if(isset($_POST['Submit'])) {
            echo 'ajax success';
        } else {
            echo "<p class='error'>nothing submitted</p>";
        }
    die();
    }

And my javascript action:

$(document).ready(function(){
    $("#contact_form").validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            message: "required"
        },
        messages: {
            name: "Please enter your name",
            email: {
                required: "Please enter your email adress",
                email: "Please enter your valid email adress"
            },
            message: "Please enter a short message, what your inquiry is about"
        },
        submitHandler: function(form) {
            $('#loading_icon').show();
            $('#click').hide();
            var params = $(form).serialize();
            $.ajax ({
                type: 'POST',
                url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                data: params,
                success: function(response) {
                    $('#response').hide();
                    $('#response').html(response);
                    $('#response').fadeIn('slow');
                    $('#loading_icon').hide();                      
                }
            });
        }

    });
});

The needed files are loaded correctly (/1.10.1/jquery.min.js, jquery.validate.js) but, this code keeps returning 0 despite the fact that I have wp_ajax_nopriv_sendmail in functions.php. The console does not return any error. I believe that I am missing some wp-specific fact, but which?

Thanks in advance

5
  • Your code doesn't use the sendmail action callback you defined. Additionally 0 is returned in case a action callback isn't found.
    – Nicolai
    Jun 4 '14 at 12:08
  • Oh can you clarify a little bit? Do you mean in js or functions? I tested with the function just echoing 'function fired' (I also implemented the change from the answer below)
    – Owl
    Jun 4 '14 at 13:04
  • 2
    You need to add the action param for your AJAX hook to fire: data: params + "&action=sendmail", Jun 4 '14 at 13:06
  • @TheDeadMedic THX so much! Now I see the response from the function!! I unfortunatedly cannot upvote, but its sure worth it
    – Owl
    Jun 4 '14 at 13:08
  • I see @TheDeadMedic did the clarification, I kind of thought what I was saying is clear, wrong assumption I guess.
    – Nicolai
    Jun 4 '14 at 13:24
1

WordPress is running Jquery in noconflict mode. (WordPress Codex Reference) or read this brief article I posted some time ago. View it here.

You need to replace:

$(document).ready(function(){

With this:

jQuery(document).ready(function($){

So all together, try this:

jQuery(document).ready(function($){
    $("#contact_form").validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            message: "required"
        },
        messages: {
            name: "Please enter your name",
            email: {
                required: "Please enter your email adress",
                email: "Please enter your valid email adress"
            },
            message: "Please enter a short message, what your inquiry is about"
        },
        submitHandler: function(form) {
            $('#loading_icon').show();
            $('#click').hide();
            var params = $(form).serialize();
            $.ajax ({
                type: 'POST',
                url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                data: params + "&action=sendmail",
                success: function(response) {
                    $('#response').hide();
                    $('#response').html(response);
                    $('#response').fadeIn('slow');
                    $('#loading_icon').hide();                      
                }
            });
        }

    });
});
6
  • Your first link doesn't address the Codex, like the text suggests. Fixed it, instead of just complaining. :)
    – Nicolai
    Jun 4 '14 at 12:13
  • My pleasure, it is supposed to be collaborative anyway.
    – Nicolai
    Jun 4 '14 at 12:29
  • Thanks I changed the line, but still the response is just 0 .. see also comment below the question, thank you so much! Eager to learn more
    – Owl
    Jun 4 '14 at 13:04
  • I also changed all $ in the code to jQuery like in your article, but still the same
    – Owl
    Jun 4 '14 at 13:07
  • Now its working, see comment from TheDeadMedic ... thanks so much, I would upvote if I could
    – Owl
    Jun 4 '14 at 13:09
0

The line bellow probably does not read your action correctly that is why it returns 0

url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: params + "&action=sendmail",

Consider making an AJAX request similar to this:

// the value of 'action' is the key that will be identified by the 'wp_ajax_' hook 
var data = {
    'action': 'my_action',
    'message': 123
};

var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.post(ajaxurl, data, function(response) {
    // Output the response which should be 'Hellow World'
    alert(response);
});

Then in your callback:

// Check if set and if the received value is 123
if (isset($_POST['message']) && $_POST['message'] == 123 ) {
    echo 'Hello World';
}
// Always exit to avoid further execution
exit(); 

I found a very simple tutorial that pretty much describes the proper way of implementing AJAX in your WordPress blog: Implementing AJAX in WordPress

3
  • "I found a very simple tutorial" talking about a tutorial you wrote is very bad and looks like spam for SEO.
    – cybmeta
    Jan 9 '15 at 7:47
  • @cybmeta sometimes people (gasp) blog what they know about WordPress! It looks perfectly fine to me, on top of very nice answer here. :) Although I would appreciate more upfront disclosure than "I found" indeed.
    – Rarst
    Jan 9 '15 at 8:12
  • Of course, I have no problem with people blogging or posting external links for reference or for more information; I do. But reading the question, the accepted answer and this one, I really think that the purpose was only insert the link. Just my opinion.
    – cybmeta
    Jan 9 '15 at 8:31

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.