K
K
karelina-nat2020-08-12 09:32:57
WordPress
karelina-nat, 2020-08-12 09:32:57

Why does the debugger give var is not defined?

The layout of the site is stretched on WordPress. One of the pages needs to load posts via ajax.
Implemented like this:
- on the page where the loading

<?php


$args = array(
  'post_type' => 'celye_torty',
    'posts_per_page' => 2,
);
 
$myquery = new WP_Query($args); 


if($myquery->have_posts()): 
  while($myquery->have_posts()):
        $myquery->the_post();
        get_template_part( 'template-parts/cakes-posts', get_post_format() );
       
  endwhile;
endif;

?>

<?php if ($myquery->max_num_pages > 1): ?>
  <script id="true_loadmore">
  var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
    var true_posts = '<?php echo serialize($myquery->query_vars); ?>';
    var current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>;
    var max_pages = '<?php echo $myquery->max_num_pages; ?>';
  </script>
<?php endif;?>


- in functions.php
function true_load_posts(){
    
    $args = unserialize( stripslashes( $_POST['query'] ) );
  $args['paged'] = $_POST['page'] + 1; // следующая страница
    $args['post_status'] = 'publish';
    

  query_posts( $args );
  // если посты есть
  if( have_posts() ) :
 
    // запускаем цикл
    while( have_posts() ): the_post();
 
            get_template_part( 'template-parts/cakes-posts', get_post_format() );
 
    endwhile;
 
  endif;
  die();
}
 
 
add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');


- in the script file

$(window).scroll(function () {
     var bottomOffset = 1000; // отступ от нижней границы сайта, до которого должен доскроллить пользователь, чтобы подгрузились новые посты
     var data = {
         'action': 'loadmore',
         'query': true_posts,
         'page': current_page
     };
     if ($(document).scrollTop() > ($(document).height() - bottomOffset) && !$('body').hasClass('loading')) {
         $.ajax({
             url: ajaxurl,
             data: data,
             type: 'POST',
             beforeSend: function (xhr) {
                 $('body').addClass('loading');
             },
             success: function (data) {
                 if (data) {
                     $('#true_loadmore').before(data);
                     $('body').removeClass('loading');
                     current_page++;

                     openModal(); // вызов функции открытия модального окна

                     if (current_page == max_pages) $('.menu-content__preloader').remove(); // если последняя страница, удаляем кнопку
                 } else {
                     $('.menu-content__preloader').remove(); // если мы дошли до последней страницы постов, скроем кнопку
                 }
             }
         });
     }
 });


On the page for which this load is intended, everything is fine, on other pages it gives
Uncaught ReferenceError: true_posts is not defined
.

How to fix?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
karelina-nat, 2020-08-12
@karelina-nat

Everything turned out to be very simple.
We conclude the script in JS in checking the condition for the existence of a variable

if (typeof true_posts !== 'undefined') {
     $(window).scroll(function () {
         var bottomOffset = 1000; // отступ от нижней границы сайта, до которого должен доскроллить пользователь, чтобы подгрузились новые посты
         var data = {
             'action': 'loadmore',
             'query': true_posts,
             'page': current_page
         };
         if ($(document).scrollTop() > ($(document).height() - bottomOffset) && !$('body').hasClass('loading')) {
             $.ajax({
                 url: ajaxurl,
                 data: data,
                 type: 'POST',
                 beforeSend: function (xhr) {
                     $('body').addClass('loading');
                 },
                 success: function (data) {
                     if (data) {
                         $('#true_loadmore').before(data);
                         $('body').removeClass('loading');
                         current_page++;

                         openModal(); // вызов функции открытия модального окна

                         if (current_page == max_pages) $('.menu-content__preloader').remove(); // если последняя страница, удаляем кнопку
                     } else {
                         $('.menu-content__preloader').remove(); // если мы дошли до последней страницы постов, скроем кнопку
                     }
                 }
             });
         }
     });
 }

P
Programiker, 2020-08-12
@Programiker

empty variable

N
nokimaro, 2020-08-12
@nokimaro

Either the PHP condition is not met (pages no more than 1) and, accordingly, the variable is not defined
<?php if ($myquery->max_num_pages > 1): ?>
. Or there are problems with the scope, and true_posts, which is still defined, is not available inside the function.
first, open the source code of the page and see if it is there
var true_posts = итд

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question