Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a form with ajax in Wordpress

I am trying to get the results of an ajax request in wordpress, but I am getting result of '0' in an alert box of javascript, so the form looks like this:

<form class="form" id="ajax-contact-form" action="#">                            
        <input type="text" name="name" id="name"  placeholder="Name" required="">
        <button type="submit" class="btn">Submit</button>
</form>

The javascript looks like this:

$('#ajax-contact-form').submit(function(e){

    $.ajax({ 
         data: {action: 'contact_form'},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              alert(data); // This prints '0', I want this to print whatever name the user inputs in the form. 

        }
    });

})

And the PHP:

add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');

function contact_form()
{
echo $_POST['name'];    
}

Does anyone know if the code above is correct, I have also tried $_REQUEST['name'] and it doesnt work.

Thanks soo much,

like image 735
MariaZ Avatar asked Sep 13 '13 03:09

MariaZ


People also ask

What is AJAX form submission in WordPress?

Ajax, short for Asynchronous Javascript and XML, is a JavaScript programming technique which allows developers to transfer data without reloading a page. It is most commonly used in web forms allowing users to submit form data without reloading a page.

How would you make an AJAX call to submit a form?

Answer: Use the jQuery $. post() Method You can simply use the $. post() method in combination with the serialize() method to submit a form using AJAX in jQuery. The serialize() method creates a URL encoded text string by serializing form values for submission. Only "successful controls" are serialized to the string.

How do I send an AJAX request on WordPress?

In WordPress, we send all AJAX request to a common URL, then wordpress internally calls the corresponding method according to the parameters which we have sent with the request. You can use the admin_url( 'admin-ajax. php' ) function of WordPress to get this url.


2 Answers

Try something like this, you did not add the name parameter you are expecting in your PHP contact_form function, so you must add it to the data attribute in the jQuery ajax function call.

$('#ajax-contact-form').submit(function(e){
    var name = $("#name").val();
    $.ajax({ 
         data: {action: 'contact_form', name:name},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              console.log(data); //should print out the name since you sent it along

        }
    });

});
like image 186
Sterling Archer Avatar answered Sep 30 '22 23:09

Sterling Archer


Revisiting the answer, year 2022. The Accepted answer is accepting BLINDLY any AJAX request without verifying WordPress Nonces. AJAX request should be validated as a legitimate request instead of a potentially nefarious request from some unknown bad actor.

  • @see https://developer.wordpress.org/plugins/javascript/enqueuing/#nonce

The first thing your AJAX handler should do is verify the nonce sent by jQuery with check_ajax_referer(), which should be the same value that was localized when the script was enqueued.

First we pass the AJAX url and create and pass our nonce through wp_localize_script(). wp_localize_script() must be called after the script has been registered using wp_register_script() or wp_enqueue_script().

<?php

wp_localize_script( 'script', 'localize',
    array(
        '_ajax_url' => admin_url( 'admin-ajax.php' ),
        '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
    )
);

From our script.js file we declare our AJAX function.

$(function(){
    $('button').click(() => {
        $.ajax({
            type: 'POST',
            url: localize._ajax_url,
            data: {
                _ajax_nonce: localize._ajax_nonce,
                test: 'test',

                /**
                 * The action parameter is the The dynamic portion of the wp_ajax_{$action} action hook (Ajax action callback being fired).
                 * 
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
                 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/
                 */
                action: '_POST_action',
            },
            success: (res) => {
                console.log(res);
            }
        });
    });
});

And we process the result and send a JSON response back to an Ajax request.

<?php

add_action( 'wp_ajax__POST_action', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $test = $_POST['test'];

        //...

        wp_send_json_success();

    } else {
        
        wp_send_json_error();

    };

} );
like image 38
amarinediary Avatar answered Sep 30 '22 23:09

amarinediary