Reputation: 1091
I am working on WordPress to retrieve subcategory when user select main category from drop down list. All work is done using ajax. But problem is if I mention dataType to json nothing return and if don't than it work as expected and I know that I am receiving valid Json.
Here is jQuery code:
jQuery(document).ready(function($) {
var select = $('#main_cat');
select.on('change', function(){
var temp = $('#main_cat option:selected').text();
console.log(temp);
var data = {
action: 'my_action',
security: '<?php echo $ajax_nonce; ?>',
cat: temp
};
$.ajax({
url: ajaxurl,
data: data,
type: 'post',
success: function(response){
console.log(response);
}
});
});
});
And this is response I am receiving. It appear to be array but when I use typeOf(response) it shows string. I also tried instanceofArray and same thing.
Here the exact response code: If I use json_encode this is what i receive but jquery still consider it string.
[" <option>Auto mobile<\/option>"," <option>Shopping<\/option>"]
and this is what i am receiving with json_encode
Array
(
[0] => <option>Auto mobile</option>
[1] => <option>Shopping</option>
)
Here is PHP code .
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
check_ajax_referer( 'my-special-string', 'security' );
$args = array(
'child_of' => get_cat_ID($_POST['cat']),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
);
$temp = array();
foreach (get_categories($args) as $cat) {
$temp[] = " <option>$cat->cat_name</option>";
}
print_r($temp);
}
Upvotes: 0
Views: 63
Reputation: 23836
I believe you are using print_r()
in backend PHP code:
When you are using datatype
in ajax
Try this in backend:
echo json_encode($output_array);
Upvotes: 0
Reputation: 1018
That response isn't JSON
. Looks like PHP print_r
, use
echo json_serialize($output);
$output
being the variable you were using print_r
on.
Upvotes: 1