Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to key value of returned array from the ajax response

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

like image 784
Mathieu Mourareau Avatar asked Apr 18 '19 14:04

Mathieu Mourareau


Video Answer


1 Answers

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']);
like image 151
Zakaria Acharki Avatar answered Oct 29 '22 03:10

Zakaria Acharki