Error when working with AJAX

Here’s my code in setup.php:

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
    wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);

    // AJAX Setup
    if ( is_search() ) {   
        wp_enqueue_script('ajax', asset_path('scripts/ajax.js'), ['jquery'], null, true);
    }

    wp_localize_script( 'ajax', 'ajaxObject', array(
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ) );

, 100);

// Define a variable that will store data from AJAX
$GLOBALS['newData'] = null;
function get_newData_handler() {
    $GLOBALS['newData'] = $_POST['newData'];
    wp_die();
}
add_action( 'wp_ajax_get_newData', 'get_newData_handler' );
add_action( 'wp_ajax_nopriv_get_newData', 'get_newData_handler' );

And ajax.js:

jQuery(document).ready( function($) {
	$(".toBeClicked").on('click', function() {
		jQuery.ajax({
			type: 'POST',
			url: ajaxObject.ajax_url,
			data: { action: "get_newData", newData: 'This is a new data' },
			success: function() {
				console.log("success");
			},
		});
	});
})

The problem is that when I run yarn start oryarn build I get the error:
error 'ajaxObject' is not defined no-undef

Can anyone point out what I set up incorrectly?

add "ajaxObject": true to https://github.com/roots/sage/blob/master/.eslintrc.js#L5

4 Likes