Basic ajax call in WordPress

My aim is to create the most simple ajax call in WordPress, but I can’t get my head around how it works.

JS File:

jQuery("#votepostform").submit(function() {

    var url = "file.php"; // php script to handle form

    jQuery.ajax({
           type: "POST",
           url: url,
           data: jQuery("#votepostform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

Form HTML:

<form action="" method="post" id="votepostform" />
    <input type="hidden" name="postid" value="333" />
    <button type="send" name="vote" class="vote_link"></button>
</form>

file.php:

echo '<script language=\'javascript\'>alert(\'It works! \');</script>';

How can I make this ajax code work in a WordPress site?

1 Answer
1

You have to use the admin-ajax handler to do the AJAX call.

Replace file.php in var url = "file.php"; with

yoursite.com/wp-admin/admin-ajax.php?action=simple_ajax

And in your plugin / functions.php file, add

add_action('wp_ajax_nopriv_simple_ajax','process_simple_ajax'); //for non logged in user
add_action('wp_ajax_simple_ajax','process_simple_ajax'); //for nlogged in user

function process_simple_ajax(){
    $data = $_REQUEST; // retrieve your submitted data
    wp_send_json($data); // return the processed data to the browser as json
}

Leave a Comment