Hi,
Sure, it’s incredibly simple… all I want is to have a seperate javascript file with my ajax functions in and then call these functions from my blade templates.
Firstly my config.json file where I’ve added ajax.js:
{
"entry": {
"main": [
"./scripts/main.js",
"./styles/main.scss"
],
"customizer": [
"./scripts/customizer.js"
],
"ajax" : [
"./scripts/ajax.js"
]
},
"publicPath": "/app/themes/bbc",
"devUrl": "http://bbc.localhost",
"proxyUrl": "http://localhost:3000",
"cacheBusting": "[name]_[hash:8]",
"watch": [
"app/**/*.php",
"config/**/*.php",
"resources/views/**/*.php"
]
}
Then enqueueing in my setup.php:
add_action('wp_enqueue_scripts', function () {
$ajax_params = array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('my_nonce'),
);
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);
wp_enqueue_script('sage/ajax.js', asset_path('scripts/ajax.js'), ['jquery'], null, true);
wp_localize_script( 'sage/ajax.js', 'the_ajax_script', $ajax_params );
}, 100);
The contents of ajax.js is just:
// eslint-disable-next-line no-unused-vars
function do_something(){
// eslint-disable-next-line no-undef
console.log('some function');
}
And finally on the template, well the partial to be precise:
@section('scripts')
<script>
jQuery(document).ready(function($){
console.log('ready');
do_something();
});
</script>
@stop
@yield('scripts');
And I constantly get: ReferenceError: do_something is not defined
So as you can see it’s pretty simple! I’m new to ES6, WebPack and ESLint though, so it’s probably my lack of understanding. Thanks for the tip about the ``` too! That helps
Kevin