0

I have following code in my functions.php file.

wp_enqueue_script( 'broadcast-ajax-request', get_template_directory_uri() . '/js/global.js', array( 'jquery' ) );
wp_localize_script( 'broadcast-ajax-request', 'ajaxadmin', array('ajaxurl'=> admin_url( 'admin-ajax.php' )));

add_action( 'wp_ajax_get_my_option', 'get_my_option' );
add_action( 'wp_ajax_nopriv_get_my_option', 'get_my_option' );

function get_my_option()
{
    print_r($_POST); exit;
}

And following code in global.js.

jQuery('document').ready(function(){
  jQuery("#submit_btn").click(function(){
    jQuery.ajax({
        url: ajaxadmin.ajaxurl,
        data: {'action':'get_my_option', 'test':'test'},
        type: "POST",
        success: function(response){
        }
    });
  });
});

But it always returning html code in response.

Himanshu Bhardiya
  • 1,047
  • 14
  • 37

2 Answers2

0

Script enqueues and localizations need to take place in the wp_enqueue_scripts action hook:

function so_34632421_enqueue_scripts() {
    wp_enqueue_script( 'broadcast-ajax-request', get_template_directory_uri() . '/js/global.js', array( 'jquery' ) );
    wp_localize_script( 'broadcast-ajax-request', 'ajaxadmin', array('ajaxurl'=> admin_url( 'admin-ajax.php' )));
}
add_action('wp_enqueue_scripts', 'so_34632421_enqueue_scripts');

Read more in the Codex.

rnevius
  • 26,578
  • 10
  • 58
  • 86
0

This is definitely a late reply, but hopefully it can help someone.

When you localize the Wordpress admin ajax url, you are setting a variable that is inserted by Wordpress into your page as such:

/* <![CDATA[ */
var bookingajax = {"ajax_url":"http:\/\/localhost:8888\/wp-admin\/admin-ajax.php"};
/* ]]> */

When using admin-ajax.php is the backend of your plugin, the adminajax variable is set as such:

var ajaxurl = '/gss/wp-admin/admin-ajax.php',

The best way to check if the ajax url has been localized is to print to the console the variable you have set.

In my example, I have set localized my admin-ajax.php using bookingajax.

if you print this variable to with console.log(bookingajax), you will see that this is now stored in a javascript object.

And here is the solution!

In your example above, you are still using the adminajax variable. You will need to add the underscore that is set in the variable stored in the frontend as such.

var ajaxurl = bookingajax.ajax_url;

jQuery.ajax({
        url: ajaxurl,
        data: {'action':'get_my_option', 'test':'test'},
        type: "POST",
        success: function(response){
        }
    });
Zac Fair
  • 1
  • 2