How to Use JSON With AJAX?

I've defined a PHP callback function to handle the communication between server-side and client-side:

function json_render_modal_body() {

    check_ajax_referer( THEME_PREFIX . '-modals', 'nonce' );

    $response = array( 'text' = 'no' );
    $modal_id = null;

    if ( isset( $_GET['modal_id'] )  ! $modal_id = filter_var( $_GET['modal_id'], FILTER_SANITIZE_STRING ) ) {
        wp_send_json_error( $response );
    }

    if ( ! $form = render_form( $modal_id ) ) {
        wp_send_json_error( $response );
    }

    $response['text'] = 'yes';

    wp_send_json_success( $response );

}

I've told WordPress about this function, to handle the communication process:

add_action( 'wp_ajax_json_render_modal_body', __NAMESPACE__ . '\json_render_modal_body' );
add_action( 'wp_ajax_nopriv_json_render_modal_body', __NAMESPACE__ . '\json_render_modal_body' );

I've registered/enqueued/localized my JS script to handle the AJAX request.

This is what I've localized:

wp_localize_script(
    THEME_PREFIX . '-modals',
    'mbe_theme_modal',
    array(
        'ajax_url' = admin_url( 'admin-ajax.php' ),
        'nonce' = wp_create_nonce( THEME_PREFIX . '-modals' )
    )
);

This is what my JS script looks like:

var modal_id = jQuery( e.relatedTarget ).attr( "data-target" ).replace( "#", "" );

jQuery.get(
    mbe_theme_modal.ajax_url,
    {
        action: "json_render_modal_body",
        modal_id: modal_id,
        nonce: mbe_theme_modal.nonce
    },
    function ( data ) {

        console.log( data );

    },
    'json'
);

Any idea why I keep getting a 0 in my AJAX response?

I've also tried removing the nonce stuff from my code, and accessing the direct URL (domain.com/wp-admin/admin-ajax.php?action=json_render_modal_bodymodal_id=some-modal-id, however, I still continue to get a 0.

I've even tried keeping the PHP function super simple with nothing but a simple text response, and still continue to get a 0.

Topic json ajax jquery wp-admin Wordpress javascript

Category Web


Usually, you can use the global variable ajaxurl instead of any path using admin-ajax.php.

More importantly, the PHP function should echo the response before calling wp_die(). Because you haven't called wp_die(), AJAX is probably waiting for more from PHP.

Hope this helps.

P.S. What is that 'json' string doing where the AJAX fail() function should be?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.