Wordpress myAjax not defined

I am working on a child theme and add the following code for ajax js admin

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 he gave me an error, for example

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

I used the 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]);
      }

    });
});

since I can solve this problem in my WordPress WordPress theme.

+4
source share
2 answers

Try the following:

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, the code above localized the object: 'myAjax' in the script "custom". and you can access the "ajax_url" property by adding the code below to the user script file.

in custom.js

alert(myAjax.ajaxurl);
+5
source

Instead admin_scriptuse ajax-scriptlike this

wp_localize_script( 'ajax-script', 'myAjax',array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

wp_enqueue_script('ajax-script');, ajax script.

0

Source: https://habr.com/ru/post/1662368/


All Articles