Enqueue script dinamically

There’s a fundamental misunderstanding of what AJAX does.

You cannot enqueue scripts directly from the PHP called from the javascript. You need to print something that can be used by the javascript making the AJAX call.

You can then use javascript to add that file to the DOM.


functions.php

//* Enqueue Ajax call on wp_enqueue_scripts hook
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_call' );
function enqueue_ajax_call() {
    wp_register_script( 'enqueue-ajax-call', PATH_TO . 'ajax-call.js', [ 'jquery' ] );
    wp_localize_script( 'enqueue-ajax.call', 'ajax_call', [ 'ajaxurl' => admin_url(' admin-ajax.php' ) ] );        
    wp_enqueue_script( 'enqueue-ajax-call' );
}

//* Print the button script on the AJAX request.
add_action('wp_ajax_nopriv_buttonscript', 'enqueue_button_script');
add_action('wp_ajax_buttonscript', 'enqueue_button_script');
function enqueue_button_script(){
   echo PATH_TO . 'button-script.js';
   wp_die();
}

ajax-call.js

//* Ajax call
(function ($) {
"use strict";
  $( document ).on( 'click', '.button', function() {
    $.ajax({
      url : ajax_call.ajax_url,
        data : {
          action : 'buttonscript',
        },
      },
      function(filename){
        // Do something useful with the filename
        var script = document.createElement( 'script' );
        script.setAttribute( "src", filename );
        document.getElementsByTagName( "head" )[0].appendChild( script );
      });
  });
})(jQuery);