How do I change the text of an output using if statements in jQuery?

Viewed 41

I've implemented a Wishlist functionality on a site, heavily based on this tutorial Tuts Plus Create AJAX Wishlist Plugin. It's working as expected, apart from the stock output from the Rest API call - it returns "instock" or "outofstock" and I'm banging my head against a brick wall trying to work out how to get it to return a formatted string (e.g. "In stock!" wrapped in a span) instead. I spent most of yesterday trying to format it in any way I know how with no success.

Here are the relevant parts of the code in the plugin PHP file:

register_rest_field('product',
            'stock',
            array(
                'get_callback'    => 'rest_stock',
                'update_callback' => null,
                'schema'          => null
            )
        );

and

function rest_stock($object,$field_name,$request){

        global $product;

        $id = $product->get_id();

        if ($id == $object['id']) {
            return $product->get_stock_status();
        }
    }

The result is output via this simplified JS:

.done(function(response){
            $('.wishlist-items').each(function(){
                var $this = $(this);
                $.each(response,function(index,object){
                    $this.append('<li class="wishlist-item" data-product="'+object.id+'"><span class="wishlist-item-stock">'+object.stock+'</span></li>');
                });
            });
        })

Can someone please point me in the right direction?! Thank you!

1 Answers

Thanks to @CBroe for the direction, I succeed with:

function rest_stock($object,$field_name,$request){

    global $product;

    $id = $product->get_id();
    $status = $product->get_stock_status();

    if ($id == $object['id']) {
       
        if ( 'instock' == $status ) {
           $stockformatted = '<span class="wishlist-is">In stock!</span>';
        }

        if ( 'outofstock' == $status ) {
            $stockformatted = '<span class="wishlist-oos">Out of stock</span>';
        }
           
        return $stockformatted;
    }
}
Related