Returns the PHP array after the AJAX call

advertisements

I'm sending an JS object via $.post() and I want to get an array back.

JS

var ajaxData = {action:"createuser"}
$("input[required]").each(function(){
    var attr = $(this).attr("name");
    ajaxData[attr] = $(this).val();
});
$.post(
    daten.ajaxurl,
    ajaxData,
    function(data){
       alert(data[0])
    }
 )

PHP

//Create a User
add_action('wp_ajax_nopriv_createuser','createuser');
function createuser () {
    foreach ($_POST as $key => $value) {
        if(empty($value)) {
            $type = "error";
            $content = "$key is empty";
            echo array($type,$content);
            wp_die();
        }
    }
}

What I get as a response is always a string, so it works well if I echo $content.

I've read about that you can use JSON and get it automatically encode if you add DataTaype: "JSON".

But I have no idea how to properly decode it in PHP, tho


I would use the wp_send_json(); function. This is exactly the thing you look for.

And don't forget to put wp_die() at the end.

wp_send_json(): https://codex.wordpress.org/Function_Reference/wp_send_json

wp_die(): https://codex.wordpress.org/Function_Reference/wp_die