Reputation: 277
Have a script which is adding products to a cart session and the php is returning the response back to the jquery post function. Problem is that I can't check the returned response to run through some animation.
My jquery code is:
var product = {
action: 'shs_add_to_cart',
'nonce': wp_nonce_value,
'product': product_id,
'title': product_title,
'qty': quantity.val()
};
$.post(
shsAjaxURL.ajaxurl, product,
function(status) {
var response = $.parseJSON(status);
console.log('response');
if(response == 'success') {
message.find('p').text('Item added to cart');
message.fadeIn(300);
message.delay(2500).fadeOut(300);
}
else {
message.find('p').text('Could not add to cart');
message.fadeIn(300);
message.delay(2500).fadeOut(300);
}
});
The PHP code works fine as it adds the value to the session cart
$_SESSION['cart_items'] = array(
array(
'item_id' => $product,
'item_name' => $title,
'item_qty' => $qty
)
);
header('Content-Type: application/json');
echo json_encode('success');
wp_die();
I get the following response
"success"
Can anyone help?
Upvotes: 0
Views: 47
Reputation: 674
Change your ajax with dataType json, like this:
$.ajax({
url:shsAjaxURL.ajaxurl,
data: product,
dataType: 'json',
type: 'post',
success:function(data) {
console.log(data.success);
}
});
And then in your php code:
$_SESSION['cart_items'] = array(
array(
'item_id' => $product,
'item_name' => $title,
'item_qty' => $qty
)
);
$data['success'] = "success";
echo json_encode($data);
Upvotes: 1