How to return the status "success" and other items in array in wordpress in admin-ajax.php

Asked

Viewed 29 times

0

How to return an array in ajax wordpress:

javascript


 $(document).on("click", "[data-show-home-list-series]", function () {
                var id = $(this).attr("data-show-home-list-series");
                $("[data-show-home-list-series]").removeClass("active");
                $(this).addClass("active");
                var $list = $("#homeSliderSerieList");
                $.post("wp-admin/admin-ajax.php", { getItems: id }, function (html) {
                    var data = jQuery.parseJSON(html);
                    if (data.status == "success") {
                        var listing = data.list;
                        var lister = [];
                        for (var i = 0; i < 20; i++) {
                            var row = listing[i];
                            lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
                        }
                        $list.parent(".itemsList").addClass("fadingOut");
                        setTimeout(function () {
                            $list.html(lister.join(""));
                            $list.trigger("destroy.owl.carousel");
                            createItemSlider();
                            $list.parent(".itemsList").removeClass("fadingOut");
                        }, 200);
                    } else {
                        return false;
                    }
                });
            });

    

PHP no wordpress, wp-admin/admin-ajax.php

function getItems(){
//{"status":"success","list":{}}
}

add_action( 'wp_ajax_getItems', 'getItems' );
add_action( 'wp_ajax_nopriv_getItems', 'getItems' );

I thank you in advance! Thank you!

2 answers

0

You can use the function wp_send_json_success()

function getItems()
{
    $items = array(
        // Sua lista completa de itens
    );

    // Eu não colocaria o campo "status" recebendo success, pois você pode tratar pelo status code do request mas fica a seu critério
    wp_send_json_success(array('status' => 'success', 'items' => $items));
    wp_die();
}

add_action( 'wp_ajax_getItems', 'getItems' );
add_action( 'wp_ajax_nopriv_getItems', 'getItems' );

0

Opa, from what I saw there in the code you want to catch a json coming from php, it’s quite simple.

function getItems(){
   //sua lógica para pegar os dados talvez
   return $seus_dados;
}

echo json_encode( getItems() ); // vai imprimir um json como resultado
exit(); // aqui você acaba com o arquivo pra nao ter nenhum conflito com outro dado que nao seja o json

You can also give a echo and exit() from within the function, there is at your discretion, but this is how you do to return a json and read at the front.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.