I'm going crazy, I haven't worked with Json files in a long time and I practically forgot how to do it.
From Laravel I am doing a query, and I want to return this query as a JSON .
public function edit($id){
$Medico = Medicos::all()->where('ID',$id)->toJson();
return Response()->json($Medico);
}
I am making the request with an httpRequest from Javascript :
function cargarModal(){
const http = new XMLHttpRequest();
const url = "/Medicos/1/edit";
http.onreadystatechange = function(){
if (this.readyState==4 && this.status == 200) {
let Medico = this.responseText;
console.log(Medico);
}
}
http.open('GET', url);
http.send();
}
In the console it returns a Json , but strange...
"[{\"ID\":1,\"centromedico_id\":1,\"user_id\":1,\"especialidad_id\":1,\"nombre\":\"Pepito\",\"apellidos\":\"Perez\",\"carnet\":1037,\"fechanacimiento\":\"199-02-30\",\"telefono\":75875,\"fichas\":10,\"created_at\":null,\"updated_at\":null}]"
I say weird , because I don't remember that a Json has backslashes.
The problem is that I don't know how to print the data, that is, I don't know how to print the name, surname, ID and so on... I was looking for information, but nothing works for me, I don't know what I'm doing wrong. Please help.
The value that you are returning from your API is as text (
responseText
) to use it in javascript you must first convert it to an object withJSON.parse(tu_json)
.Once converted into an object you can access your data normally as you access the properties of an object, example: