While working with WordPress AJAX in initial level most of developers face the error “ajaxurl is not defined”. Here we will see how to solve this error.

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: ajaxurl,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});

1. wp_localize_script

function my_enqueue() {

    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );

    wp_localize_script( 'ajax-script', 'cc_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

Script.js file

jQuery.ajax(
    {
        type: "post",
        dataType: "json",
        url: cc_ajax_object.ajax_url,
        data: formData,
        success: function(msg){
            console.log(msg);
        }
    });

Here we have used “cc_ajax_object” as object.

2. Direct Plugin or Theme File

Put the following code in your function.php file.

add_action('wp_head', 'codecanal_ajaxurl');

function codecanal_ajaxurl() {
    echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
There are currently no comments.