Fetch and show multiple custom fields via AJAX

To pass data from js back to PHP simplest way is use json_encode or, in WP, its wrappers wp_send_json, wp_send_json_error and wp_send_json_success.

Usage example:

On PHP side

function get_latest_product_meta() {

    $post_id = (int) filter_input(INPUT_GET, 'post_id', FILTER_SANITIZE_NUMBER_INT);
    $post_id or wp_send_json_error();

    // array_shift because when used like so `get_post_meta` return array of arrays...
    $data = array_map('array_shift', get_post_meta($post_id));
    wp_send_json_success($data);
}

On js side

$(document).ready( function() {
    $.ajax({
        type : "GET",
        url : ajax_object.ajaxurl,
        data : { action : "ajax-get-latest-price" },
        success: function ( result ) {
            if (result.error) {
               alert('Post not found!');
            } else if(result.success) {
               $('span.price').html( result.data.price );
               $('span.seller').html( result.data.seller);
               // and so on....
            }
        }
    });
});

Leave a Comment