how to call function in ajax php code example

Example 1: ajax call too functions.php

var ajaxurl = 'https://example.com/wp-admin/admin-ajax.php';
    $.ajax({
        url: ajaxurl,
        type: 'post',
        data: { action: 'register_user' ,"username": "arshia"},
        success: function(response) { console.log(response); }
    });

Example 2: ajax call too functions.php

<?php
    // ajax call to this function
    function register_user()
    {
        $username = $_POST['username'];
        echo $username;

        die();
    }

    add_action('wp_ajax_register_user', 'register_user');
    add_action('wp_ajax_nopriv_register_user', 'register_user');
    
?>