AJAX and JSON: json_decode() returns null in WordPress
You pass an array from PHP with json_encode() through AJAX, and on the other side json_decode() returns null, or the data has the wrong types. In my case the cause was in the data itself: numbers that were strings instead of integers. Below is that case, and a checklist for the other common causes.
Problem: When transferring an array through AJAX with json_encode(), the receiving side gets null from json_decode() or data of the wrong type.
Check the data types with var_dump()
The first step is to look at what exactly you encode. var_dump() shows the types. In my case it was:
array(2) { [0]=> string(3) "212" [1]=> string(3) "211" }
and it should have been:
array(2) { [0]=> int(212) [1]=> int(211) }
Where the strings came from
The situation arose because of this code:
$args = array(
'post_type' => 'custom_post_type',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
);
$custom_post_type = new WP_Query( $args );
if ( $custom_post_type->have_posts() ) {
$custom_post_type_ids = array();
while ( $custom_post_type->have_posts() ) {
$custom_post_type->the_post();
$custom_post_type_ids[] .= $post; // .= turns the value into a string
}
wp_reset_postdata();
}
The .= operator is string concatenation, so every ID becomes a string. The loop isn’t needed at all: with 'fields' => 'ids', $query->posts is already an array of integer IDs:
$custom_post_type = new WP_Query( $args ); // 'fields' => 'ids' $custom_post_type_ids = $custom_post_type->posts;
If you need objects for other reasons, wp_list_pluck() extracts one field from a list of posts: wp_list_pluck( $query->posts, 'ID' ). Casting is fine too: array_map( 'intval', $ids ).
If json_decode() really returns null
String numbers are still valid JSON, so if decoding fails completely, the JSON itself is broken. Check:
- What the error is. Right after
json_decode(), calljson_last_error_msg(): “Syntax error”, “Malformed UTF-8 characters” and so on. - Extra output in the AJAX response. A PHP notice, a
var_dump()left in the code or whitespace before<?phpends up in front of the JSON and breaks it. Open the response in the browser’s Network tab and look at the raw text. - How you send the response. In WordPress AJAX handlers use
wp_send_json()orwp_send_json_success(): they set the right header, encode the data and stop execution, so nothing else gets appended. - Encoding.
json_encode()fails on strings that are not valid UTF-8, for example data imported from an old database.wp_json_encode()tries to fix the encoding before giving up.