4 votes

Process json_encode ($ data) through ajax jquery

I'm working with ajax, jquery and php; sending an ajax request to php via post, of the following form:

function obtenermail() {
    //console.log($('#destinatario').val());
    var ced = $('#destinatario').val();
    $.ajax({
        type: "POST",
        data: { 'cedula': $('#destinatario').val()},
        url: "<?php echo site_url();?>"+"/roles/obtenercorreo", 
        success : function(data) {
            console.log(data);

        }
    });
}

in php I have the following function:

public function obtenercorreo(){
    if($this->session->userdata('logueado')){
        $ced = $this->input->post('cedula');
        $data = $this->persona_model->getPersonaced($ced);
        echo json_encode($data);
    }else{
        redirect('','refresh');
    }
}

The request works correctly, shows me the array in the following way:

[{"cedula":"1100253986","nombres":"SOTO CASTILLO LAURO HERNAN","mod_laboral":"CONTRATO COLECTIVO","email":""}]

What I don't know, is how to get each value separately, because if I put

console.log(data[0])
console.log(data.cedula)
console.log(data['cedula'])

I returns undefined or an empty string.

My question is: How could I do to read each individual item? that is to say to obtain the certificate, or mail separately

6voto

Alvaro Montoro Points 38554

Now you are treating it as if it were a chain, you must validate / process that string as JSON (with JSON.parse ) and then you can access the data easily.

The changes in the JavaScript code would be like this:

 $.ajax({
    type: "POST",
    data: { 'cedula': $('#destinatario').val()},
    url: "<?php echo site_url();?>"+"/roles/obtenercorreo", 
    success : function(data) {
        var datos = JSON.parse(data);
        console.log(datos[0].cedula);
        console.log(datos[0].email);
    }
});
 

And now in the console should appear the correct value of the card and the mail.

5voto

Chofoteddy Points 3499

Despite already having the solution, I give you a recommendation (happy face).

The following code contains an AJAX call to the URL that you want and the solution you propose @Alvaro Montoro. To improve the practice of your request, we recommend that you add in your code to only 2 lines and delete 1.

The first line to add will be in Js, because you will be telling jQuery that the content type you expect (in this case JSON), and thus avoid parsing the data because you have received him as such (in JSON).

Solution

$.ajax({
    type: 'POST',
    dataType: 'json',
    data: { 'cedula': $('#destinatario').val() },
    url: "<?php echo site_url(); ?>/roles/obtenercorreo", 
    success : function(data) {
        console.log(data[0].cedula);
        console.log(data[0].email);
    }
});

The second line is in the server side, what that does is return the request content type that contains the response (JSON).

header('Content-Type: application/json');
echo json_encode($data);

Thank you that this type of practice, you can detect errors as when the server does not answer a JSON object to handle it differently, that in such a case, would the function error of the AJAX.

1voto

Josh_zarate Points 36

You can save a line in this way:

 success : function(data) {
        console.log(data.cedula);
        console.log(data.email);
    }
 

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X