I am working with ajax, jquery and php; I send an ajax request to php through post, like this:
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, it shows me the arrangement as follows:
[{"cedula":"1100253986","nombres":"SOTO CASTILLO LAURO HERNAN","mod_laboral":"CONTRATO COLECTIVO","email":""}]
What I don't know is how to get each value separately, since if I put
console.log(data[0])
console.log(data.cedula)
console.log(data['cedula'])
returns me undefined or an empty string .
My question is: How could I go about reading each individual item? that is, obtain the cedula, or the mail separately
Right now it is treating it as if it were a string, you need to validate/process that string as JSON (with
JSON.parse
) and then you can easily access the data.The changes in the JavaScript code would be like this:
And now the correct value of the ID and the mail should appear in the console.
Despite already having the solution, I give you a recommendation (smiley face).
The following code contains an AJAX call to the URL you want and the solution proposed by @Alvaro Montoro. To improve the practicality of your request, I recommend that you add only 2 lines to your code and delete 1.
The first line to add will be in Js, because you will tell jQuery what type of content you expect (in this case JSON) so you avoid parsing the data because you receive it as such (in JSON).
Solution
The second line is on the server side, what it does is return the type of content contained in the response (JSON) in the request.
Thanks to this type of practice, you can detect errors such as when the server does not respond to a JSON to handle it in a different way, which in that case, the AJAX error function would be activated.
You can save a line like this: