I make a request in ajax at the click of the button passing the id of a product to a controller and it passes to the helper. In the helper, through this id of the product I add it to the cart, but that does not matter much on that issue. I create an array of data in this helper and return it, and the controller returns that array to the request. But when I give an alert in the array so I can see what it upsets me, it returns me a null value and I do not know why that happens.
Ajax request:
function addCartao(product_id){
alert("entrou");
alert(product_id);
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/teste') ?>",
data: {
product_id: product_id
},
dataType: 'json',
cache : false,
beforeSend: function () {
alert("beforeSend");
},
success: function (dados) {
alert("success");
alert(dados);
},
complete: function () {
alert("complete");
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
Controller:
$product_id = $this->getRequest()->getPost();
echo json_encode(Mage::helper('fol_carousel/cartao')->addCustom($product_id));
Array created in the helper:
$dados['product_name'] = "teste";
$dados['product_price'] = "2.99";
return $dados;
Every time the ajax request alert
is executed, it returns me null.
3
Answers
The solution I found to the problem was by changing the return variable of my ajax request on its success and specifying an array position. Doing this by giving the
alert
in the array, it returns me value.Ajax request code with modifications:
Open the developer tool and check what is there in the response of server call.
Verify that your server code is receiving parameter that you posted and returning proper data.
You are getting null because the data you are received in the client side as ajax response is not a valid JSON data. According to what I understood from your comments, when you hard coded a json value in server side you are getting the JSON object in the client side as response, that’s perfect. So the issue is with the server side JSON response data which is not valid.