Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTravis Thompson
12,976 PointsAdding AJAX to a Plugin - Challenge Task 5 of 6
The challenge states: Create a function named my_plugin_enable_ajax. After the opening {, close the PHP block. Then, before the closing }, open a new PHP code block. Between the closing and opening PHP blocks, write out opening and closing script tags. Inside of them, create a JS variable named ajaxurl and assign it the admin-ajax.php file using the admin_url function.
Here is my code below:
<?php
function my_plugin_frontend_scripts() {
wp_enqueue_style( 'my_plugin_frontend_css', plugins_url( 'my-plugin/css/front-end.css') );
wp_enqueue_script( 'my_plugin_frontend_js', plugins_url ( 'my-plugin/js/front-end.js'), array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'my_plugin_frontend_scripts' );
function my_plugin_enable_ajax {
?>
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>
I am just not seeing my mistake here. If anybody could help that would be super rad! Thanks!
2 Answers
Travis Thompson
12,976 PointsAnswered my own question. More of an issue of formatting.
Correct code:
<?php
function my_plugin_enable_ajax() {
?>
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
function my_plugin_frontend_scripts() {
wp_enqueue_style('my_plugin_frontend_css', plugins_url('my-plugin/css/front-end.css') );
wp_enqueue_script('my_plugin_frontend_js', plugins_url('my-plugin/js/front-end.js'), array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'my_plugin_frontend_scripts' );
add_action( 'wp_head', 'my_plugin_enable_ajax' );
?>
Andres Ramirez
18,094 PointsThis will solve the rest of the problem...
<?php
function my_plugin_enable_ajax() {
?>
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
function my_plugin_frontend_scripts() {
wp_enqueue_style('my_plugin_frontend_css', plugins_url('my-plugin/css/front-end.css') );
wp_enqueue_script('my_plugin_frontend_js', plugins_url('my-plugin/js/front-end.js'), array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'my_plugin_frontend_scripts' );
add_action( 'wp_head', 'my_plugin_enable_ajax' );
?>
Thanks Travis!