1

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

3
  • 1
    Just do echo json_encode(array($type, $content)). I assume that's what you mean. Commented Oct 28, 2016 at 9:31
  • @Andrew now I get an object back. I assume it's a JSON object. How can I turn it into an array? Commented Oct 28, 2016 at 9:36
  • You can use JSON Parse from javascript to read the information in the json. Commented Oct 28, 2016 at 9:56

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

You are awesome! Is the wp_die() necessary, as wp_send_json() fires die() ?
You don't have to use wp_die with this function
No, it's not necessary, as wp_send_json() includes die(). But it is "best practice" - one line of code and you sleep better :D
1

You can't just echo an array. In AJAX it's considered default to return JSON objects in requests. What you want to do is make an JSON object from the array. You can use json_encode for that.

http://php.net/json_encode

After that you can use the JSON object in JS/jQuery to do whatever you want to do with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.