0

last time I fight with Ajax and WordPress. I have a problem using Ajax wants to load the Posts of the same category ... in response is replaced Object, only one entry.

Where to find the problem?

ajax.js

var $fnWritePostGrid = function (idCat) {
        var data = {
            type: 'POST',
            url: ajaxOptions.url,
            action: 'kk_load_servicesGrid',
            idCat: idCat
        };
        $.ajax({
            type: "POST",
            url: ajaxOptions.url,
            data: data,
            dataType: "json",
            success: function (response) {
                console.log(response);
            }

        });
        return false;

    };

functions.php

$cat_id = $_POST['idCat'];
$args = array(
    'category' => $cat_id,
    'posts_per_page' => 8,
    'order' => 'DESC'
);  

$posts = get_posts($args);

foreach($posts as $post) {
    $postID = sanitize_text_field($post->ID);
    $postTitle = sanitize_text_field($post->post_title);
    $postContent = sanitize_text_field($post->post_content);

    $response = array(
        'ID' => $postID,
        'title' => $postTitle,
        'content' => $postContent
    );
    echo json_encode($response);
    exit;
}

In summary, the code works but doesn't return an array of entries, only the first entry in the category.

Please help and thanks in advance.

1
  • 1
    Try outputting your JSON after the foreach loop, rather than inside it? Commented Oct 10, 2014 at 11:04

1 Answer 1

1

It looks as though your PHP is exiting the thread after the first iteration of your foreach loop:

echo json_encode($response);
exit;

What you likely want to do instead is create an array of all of the posts that you want to return -- something like this:

$responses = array();

foreach($posts as $post) {
    $postID = sanitize_text_field($post->ID);
    $postTitle = sanitize_text_field($post->post_title);
    $postContent = sanitize_text_field($post->post_content);

    $response = array(
        'ID' => $postID,
        'title' => $postTitle,
        'content' => $postContent
    );
    array_push($responses, $response)
}

echo json_encode($responses);
exit;

This way you'll actually be returning a JSON array of objects, rather than a single JSON object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.