maddy maddy - 7 days ago 5
Ajax Question

wordpress myAjax is not defined

I am working in child theme and put following code for admin ajax js

function wpb_adding_scripts() {
/* echo "string". get_stylesheet_directory_uri().'/css/jquery.bxslider.css';
exit();*/
wp_register_script('flexslider', get_stylesheet_directory_uri() . '/js/jquery.flexisel.js', array('jquery'),'1.1', true);
wp_enqueue_script('flexslider');
wp_enqueue_script('bxslider', get_stylesheet_directory_uri() . '/js/jquery.bxslider.min.js', array(),true, true);
wp_enqueue_script('bxslider');

wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/js/custom.js', array(),true, true);
wp_enqueue_script('custom');
//wp_localize_script('admin_script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );

wp_localize_script('admin_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script('admin_script');

}

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 );


but it given me error like

ReferenceError: myAjax is not defined
url : myAjax.ajaxurl,


I used myAjax declaration in my custom js..

jQuery('#load_more_posts').on('click',function(){
var lng =jQuery(".post_item").length;

jQuery.ajax({
type : "post",
url : myAjax.ajaxurl,
data : {action: "load_more_posts_home",count : lng},
}).done(function(response){
var posts = JSON.parse(response);

for( var i = 0; i < posts.length; i++ )
{
if( posts[i] == "0" )
jQuery("#load_more_posts").fadeOut();
else
jQuery("#load_more_posts").before(posts[i]);
}

});
});


so how could i resolve this issue in my wordpress child theme.

Answer

Try this:

wp_enqueue_script('custom'); //Name of the script. Should be unique.here is 'custom'
wp_localize_script('custom', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));  // remove admin_script and add unique javascript file.

Here above code localized the object:'myAjax' in script "custom". and you can access property "ajax_url" by adding below code in custom script file.

in custom.js

alert(myAjax.ajaxurl);