I´m trying to do a plugin feature : download a file by a button click using wp_ajax feature.
I already used wp_ajax but in this case I did not find my error.
When I click on the button, it runs correctly the js file, but return the html page instead to call getPrivateFileByAjax()
.
JS
jQuery( function($) {
$(document).ready( function() {
$(".download-file").on( "click", function( event ) {
var file_name = $(this).attr("data-file");
var data = {
'action': "getPrivateFileByAjax",
'file_name' : file_name
};
$.post( wgs_ajax_object.ajaxurl, data, function( response ) {
console.dir( response );
});
});
});
});
My Shortcode page
class FileDownloadsShortcode extends Shortcode {
public function check_page() {
global $post;
if( !empty( $post ) && has_shortcode( $post->post_content, $this->tag ) ){
add_action('wp_enqueue_scripts', array( $this , 'set_scripts'));
}
}
public function set_scripts() {
//Javascripts
wp_enqueue_script( "downloadsscript", "path-to-my-js.js" );
wp_localize_script( 'downloadsscript', 'wgs_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
);
}
}
Admin init file
class Admin extends FooPlugin {
public function __construct() {
parent::__construct();
add_action( "wp_ajax_getPrivateFileByAjax", array( $this, "getPrivateFileByAjax" ) );
add_action( "wp_ajax_nopriv_getPrivateFileByAjax", array( $this, "getPrivateFileByAjax" ) );
}
public static function getPrivateFileByAjax(){
echo "test";
wp_die();
}
}