Here my return json from my Ajax method :
{"id_ac":"32","mail_uniq_ac":"[email protected]","id_civ":"2"}
I would like to access to id_ac
key value in my javascript but actually, I cannot.
this is my ajax controller :
public function executeAjaxGetActeur(sfWebRequest $request){
$id_ac = $request->getParameter('id_ac');
$acteur = Doctrine_Core::getTable('Acteur')->findOneByIdAc($id_ac);
return $this->renderText(json_encode($acteur->toArray()));
}
Here is my javascript where I need to get the key values
function showModalTempsPartenaire($id_ac){
var $id_ac = $id_ac;
$.post($url + "/ajax/get_acteur", {
id_ac: $id_ac
}, function (data) {
if (data && trim(data) != '')
console.log(data);
console.log(data['id_ac'])
});
}
The :
console.log(data);
Output me :
{"id_ac":"32","mail_uniq_ac":"[email protected]","id_civ":"2"}
but console.log(data['id_ac']); return undifined
You're encoding the data to JSON in the server side using json_encode()
, you need to decode it in the client side using JSON.parse()
so you will be able to get the information from it like :
function showModalTempsPartenaire($id_ac){
var $id_ac = $id_ac;
$.post($url + "/ajax/get_acteur", {
id_ac: $id_ac
}, function (data) {
if (data && trim(data) != '')
data = JSON.parse(data);
console.log(data['id_ac'])
});
}
Working sample
var data = '{"id_ac":"32","mail_uniq_ac":"[email protected]","id_civ":"2"}';
var obj = JSON.parse(data);
console.log(obj['id_ac']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With