Can’t get a JSON object in response to an Ajax request with wp_ajax

BODA82’s answer helped, but eventually I realized that I should have replaced responseText with responseJSON method in my JavaScript code. In the example below I was storing the Ajax response results in a variable. I didn’t know there was a specific method to get the response in JSON. In a such way the object/array with get_posts() results is returned correctly and not as a string:

posts = $.ajax({
    type: 'GET',
    url: ajaxurl,
    async: false,
    dataType: 'json',
    data: { action : 'getHotelsList' },
    done: function(results) {
        // Uhm, maybe I don't even need this?
        JSON.parse(results);
        return results;
    },
    fail: function( jqXHR, textStatus, errorThrown ) {
        console.log( 'Could not get posts, server response: ' + textStatus + ': ' + errorThrown );
    }
   }).responseJSON; // <-- this instead of .responseText

Note to self, but also general advice: if you can’t fix something in the evening it’s a sign you should go to bed, read a book, and count stars. An answer will be found the next morning, the earlier the better 😀

Leave a Comment