0

I'm doing a fairly standard situation where posts are loaded with AJAX via a list. I'm having difficulty passing from WP/PHP to JS when the max posts are reached.

Here's what I use to enqueue assets in functions.php and thus, localize my script:

function news_enqueue_assets() {
    global $wp_query;
    wp_localize_script( 'sage_js', 'newsposts', array(
      'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));
}

add_action('wp_enqueue_scripts', 'news_enqueue_assets', 100);

And below that, for the AJAX post loading side of things I have:

add_action( 'wp_ajax_nopriv_news_load_posts', 'news_load_posts' );
add_action( 'wp_ajax_news_load_posts', 'news_load_posts' );

function news_load_posts () {
    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );

    $query_vars = array(
        'posts_per_page' => $_POST['number_of_posts'],
        'paged' => $_POST['page'],
        'category__and' => $_POST['category'],
        'tag__in' => $_POST['tag']
      );
    $posts = new WP_Query( $query_vars );
    $globals['wp_query'] = $posts;

    if( ! $posts->have_posts() ) { 
        echo 'No more posts';
    }
    else {
        while ( $posts->have_posts() ) { 
            $posts->the_post();
            get_template_part( 'templates/news', 'single' );
            echo 'Max post check: ' . $posts->found_posts;

        }
    }

    die();
}

Lastly, the JS:

var load_posts = function() {
            $.ajax({
                type: 'POST',
                data: {
                    action: 'news_load_posts',
                    query_vars: newsposts.query_vars,
                    number_of_posts : 4,
                    page: page,
                    category: category_id,
                    tag: get_active_tag()
                },
                url: newsposts.ajaxurl,
                beforeSend : function(){
                },
                success    : function(data){

                    $content.html(data);


                },
                error     : function(jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
                }
        });
    };

Everything works great, in general, I just can't figure out how to pass values TO the JS. I understand I can add other values to wp_localize_script, but then how do I pass those variables/values to function news_enqueue_assets() ?

A push in the right direction is hopefully all I need.

Thank you for your time!

  • 1
    rather than echo html from news_load_posts, return a json object that contains your html plus some other var that indicates whether or not more posts exist. – Milo Mar 21 '15 at 18:37
  • Pass PHP variable to javascript – Nicolai Mar 21 '15 at 19:10
  • I agree with Milo. Using JSON as format to transmit data is actually a standard and allow you to transmit any other variable you may want to be read back in javascript. In WordPress there are functions ready to be used for ajax responses using JSON: wp_send_json and its wrappers wp_send_json_success and wp_send_json_error – cybmeta Mar 21 '15 at 19:47
  • Thank you all for responding. @cybmeta @Milo Returning the JSON object sounds appropriate. Where exactly am I putting wp_send_json? Adding a basic array $test, and using wp_send_json($test) in lieu of the echo 'Max post..' kills the posts output and spits out my array directly. – Mr Bullets Mar 21 '15 at 20:15
  • wp_send_json sends the response and exit the program, so when wp_send_json is executed, the code bellow it is not triggered. Also, you can not mix a JSON response with a HTML response, so it is not as simple as adding wp_send_json to your code; more changes are needed, both PHP and javascript, to make it work with JSON. I'm sorry but it is late here and I have not energy to post an example right now, I'll come back tomorrow. – cybmeta Mar 21 '15 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.