DEV Community

Shweta Danej
Shweta Danej

Posted on • Updated on

Ajax calls in wordpress front-end

wp_ajax_ and wp_ajax_nopriv_ actions hooks are used to make ajax calls from wordpress front-end.

wp_ajax_ is used when the user is logged in to the website.
wp_ajax_nopriv_ is used when the user is logged out of the website.

You can set your ajax calls according to the need.

2 ways you can do this, let's see a quick example here:

1. Without a separate script file

You can create a file in your plugin OR you can use your theme's functions.php file for this.

When not creating a script file, you can embed the script in Wordpress footer using wp_footer action hook like this :

First of all you need to get ajaxurl to set the URL, unlike the ajaxurl javascript global does not get automatically defined in frontend.

<?php
add_action( 'wp_footer', 'my_ajax_without_file' );

function my_ajax_without_file() { ?>

    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl

        var data = {
            'action': 'frontend_action_without_file', // your action name 
            'variable_name': "Some value" // some additional data to send
        };

        jQuery.ajax({
            url: ajaxurl, // this will point to admin-ajax.php
            type: 'POST',
            data: data,
            success: function (response) {
                console.log(response);                
            }
        });
    });
    </script> 
    <?php
}

add_action("wp_ajax_frontend_action_without_file" , "frontend_action_without_file");
add_action("wp_ajax_nopriv_frontend_action_without_file" , "frontend_action_without_file");

function frontend_action_without_file(){
    echo json_encode($_POST);
    wp_die();
}

?>
Enter fullscreen mode Exit fullscreen mode

2. With separate javascript file

Create a frontend-scripts.js file and include it in the front end footer using the wp_enqueue_scripts action hook.

Localize the script to pass the PHP variables to use it in javascript code.

<?php
add_action( 'wp_enqueue_scripts', 'enqueue_my_frontend_script' );

function enqueue_my_frontend_script() {
    wp_enqueue_script( 'my-script', plugin_dir_url(__FILE__).'frontend-scripts.js', array('jquery'), null, true );
    $variables = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );
    wp_localize_script('my-script', "test", $variables);
}

?>
Enter fullscreen mode Exit fullscreen mode

Add this code to javascript file to make an ajax call and use the test.ajaxurl to set URL

jQuery(function ($) {

    var testingObj = {
        init: function () {
            testingObj.callAjaxMethod();
        },
        callAjaxMethod:function(){
            var data = {
                'action': 'frontend_action_with_file',
                'name': "Shweta"
            };

            jQuery.ajax({
                url: test.ajaxurl,
                type: 'POST',
                data: data,
                success: function (response) {
                    console.log(response);   
                }
            });
        }
    }
    testingObj.init();
});
Enter fullscreen mode Exit fullscreen mode

Check the browser console to see the result, and it's done :)

Top comments (1)

Collapse
 
lukosevicius profile image
Mantas Lukosevicius • Edited

Hi. I tried both these examples and I'm getting the same error:
POST --my-url--/wp-admin/admin-ajax.php 400 (Bad Request)

Oh, I figured it out, I had to put this to my functions.php, I tried to use it from template file. Thanks, very great examples! I'll bookmark this:)