简体   繁体   中英

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,

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

        }
    });

});

You should add an attribute for name too in your javascript.

It may look like this........

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

$.ajax({ 
     data: {action: 'contact_form', name:name},
     type: 'post',
     url: ajaxurl,      
     success: function(data) {
          alert(data); 
    }
});

})

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

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'];
        
        //...

        return wp_send_json( $value );

    };

} );

You should include this script in functions.php

wp_register_script('my_script_handle','');
wp_add_inline_script('my_script_handle', "var techy_ajaxurl = '".admin_url( 'admin-ajax.php' )."';"  );
wp_enqueue_script( 'my_script_handle' );

and in js change to this

$.ajax({ 
     data: {action: 'contact_form', name:name},
     type: 'post',
     url: techy_ajaxurl,      
     success: function(data) {
          alert(data); 
    }
});

It will work 100% tested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM