AJAX action not being called

This is how I set up my AJAX 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);

Then, in my ajax.js:

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

I defined my get_newData function and added my AJAX action in functions.php, which I am not sure if that’s best practice:

add_action( 'wp_ajax_get_newData',  __NAMESPACE__ . '\\get_newData' );
add_action( 'wp_ajax_nopriv_get_newData',  __NAMESPACE__ . '\\get_newData' );

// Define a variable that will store data from AJAX
$GLOBALS['newData'] = null;
function get_newData() {
    $GLOBALS['newData'] = $_POST['newData'];
    echo $GLOBALS['newData'];
    die();
}

Now, when I clicked element with class ‘toBeClicked’, the console does print success but I don’t think my function get_newData is getting executed because $GLOBALS['newData'] does not display on my page.

Not really sure what you’re trying to do, but you can’t set a global like that.

Your echo in get_newData() is returning the data to your AJAX request which can be fetched with:

function get_newData() {
    $response['newData'] = $_POST['newData'];
    // set_transient('newData', $_POST['newData']); // see below
    echo json_encode($response);
    wp_die();
}
success: function(response) {
    if (response.type == 'success') {
        console.log(response);
    } else {
        console.log('Error');
    }
},

as far as storing newData from the AJAX call to call inside of a template without Javascript, I guess you could set it as a temporary transient and call it with get_transient('newData') or something if you must…?

I’m trying to set $GLOBALS['newData'] to equal the string ‘New data’, which is stored in the variable newData, so then I can use that string variable in my PHP code such as echoing it.

Can you explain what you are trying to do with $response['newData'], set_transient() and json_encode($response) functions?