D
D
Danil Ostapenko2021-07-13 08:34:05
AJAX
Danil Ostapenko, 2021-07-13 08:34:05

How to get multiple variables back in AJAX in WP?

There is HTML:

60ed1a5d89db6722587989.png

When clicking on .content-view-block-wrap elements, JS gets id via id="x'

$(".content-view-block-wrap").on("click", function (event) {
    event.preventDefault();

    var hid_id = this.id;

    $.ajax({
        url: "/wp-admin/admin-ajax.php",
        method: 'post',
        data: {
            action: 'ajax_id_obj',
            hid_id: hid_id
        },
        dateType: 'JSON',
        success: function (response) {
            $('.testzone').html(JSON.parse(response.date));
            $('.testzone2').html(JSON.parse(response.test));
        }
    });
});

The script sends a handler to the file, which receives data, processes it and must return not one variable, but several:

function ajax_id_obj(){
    $hid_id = wp_strip_all_tags($_REQUEST['hid_id']);

    $date = 'тест'.$hid_id;
    $test = 'тест2'.$hid_id;

    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ){
        echo $response = json_encode( array('date'=>$date, 'test'=>$test) );;
        wp_die();
    }
}

add_action('wp_ajax_nopriv_ajax_id_obj', 'ajax_id_obj' );
add_action('wp_ajax_ajax_id_obj', 'ajax_id_obj' );


(before that, I only worked with 1 variable; everything is simple there).

Can you tell me how to solve this issue?

I rummaged through the Internet, and added dateType: 'JSON' to JS and send data via json_encode and accept as JSON.parse(response.test), but in the console it gives :

Uncaught SyntaxError: Unexpected token u in JSON at position 0
60ed1c29743ba684838184.png

PS I set the handler in PHP test variables, then I'll substitute which ones I need to return, cut out the cycle, so that the code would be shorter.
PSS In the simplified version with 1 variable, everything works, I mean that JS transfers data to the executing file and the file returns the variable.

Simplified version that works:

$(".content-view-block-wrap").on("click", function (event) {
    event.preventDefault();

    var hid_id = this.id;

    $.ajax({
        url: "/wp-admin/admin-ajax.php",
        method: 'post',
        data: {
            action: 'ajax_id_obj',
            hid_id: hid_id
        },
        success: function (response) {
            $('.testzone').html(response);
        }
    });
});


function ajax_id_obj(){
    $hid_id = wp_strip_all_tags($_REQUEST['hid_id']);


    $response = 'тест'.$hid_id;

    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ){
        echo $response;
        wp_die();
    }
}

add_action('wp_ajax_nopriv_ajax_id_obj', 'ajax_id_obj' );
add_action('wp_ajax_ajax_id_obj', 'ajax_id_obj' );

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question