Reputation: 467
I am trying to parse a JSON object received from my server. This is my server's response:
[
{
"idPais": "1",
"nombre": "España"
},
{
"idPais": "2",
"nombre": "Grecia"
},
{
"idPais": "3",
"nombre": "Holanda"
},
{
"idPais": "4",
"nombre": "Finlandia"
},
{
"idPais": "5",
"nombre": "Suiza"
}
]
In my script, I tried to get the objects with one array, but resp
is always undefined
.
function loadCountries(cont) { // Listado de paises con contenidos
var i = 0;
var method = 'GET';
var path = appConstants.requestCountriesURL(cont);
console.log(path);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
alert('Status es: ' + xhr.status + 'State es: ' + xhr.readyState);
if(xhr.readyState == 4 && xhr.status == 200) {
alert('Recogiendo respuesta...');
resp = xhr.responseText;
}
}
xhr.open(method, path, false); // Creamos la peticion
resp = xhr.send(); // Guardamos la respuesta
if(resp == false || resp == undefined) {
alert('La lista de paises no se pudo obtener');
return resp;
} else {
alert('La lista de paises se obtuvo correctamente');
console.log(resp);
var listaPaises = JSON.parse(resp);
return listaPaises;
}
}
The error shown is the following:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
Edit with solution 1:
function checkCountries(i){
alert('oncheckCountries');
var answer=$('input[name^="radio-choice"]:checked').val();
alert('val es: '+ answer);
$('#divPaises').css('display','block');
getCountries(answer);
}
function getCountries(continente){
alert('on getCountries');
loadCountries(continente);
}
function loadCountries(cont){ //Listado de paises con contenidos
var i = 0;
var method = 'GET';
var path = appConstants.requestCountriesURL(cont);
console.log (path);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
if(xhr.readyState == 4 && xhr.status == 200){
alert('Recogiendo respuesta...');
resp = xhr.responseText;
if(resp == false || resp == undefined){
alert('La lista de paises no se pudo obtener');
return resp;
}
else{
alert('La lista de paises se obtuvo correctamente');
console.log(resp);
var listaPaises = JSON.parse(resp);
console.log(listaPaises[0]);
var size = Object.keys(listaPaises).length;
var select = document.createElement('select');
alert('Select creado');
select.name = 'selectPais';
select.id = 'selectPais';
for(i=0;i<size ;i++){
var option = document.createElement('option');
option.id = listaPaises[i].idPais;
option.value = listaPaises[i].nombre;
option.appendChild(document.createTextNode(listaPaises[i].nombre));
alert(option.getAttribute('value'));
select.appendChild(option);
}
document.getElementById('divPaises').appendChild(select);
}
}
}
xhr.open(method, path, true); //Creamos la peticion
resp = xhr.send(); // Guardamos la respuesta
}
Upvotes: 2
Views: 142
Reputation: 2369
It is an asynchronous call and you are trying to handle it as a synchronous one.
xhr.onreadystatechange = function() {
alert('Status es: ' + xhr.status + 'State es: ' + xhr.readyState);
if(xhr.readyState == 4 && xhr.status == 200) {
alert('Recogiendo respuesta...');
resp = xhr.responseText;
//Do your stuff with resp here
}
}
xhr.open(method, path, false); // Creamos la peticion
xhr.send(); //Send will not return anything
Check here if you want more examples: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Upvotes: 1
Reputation: 69377
Your issue here is that you are using the result of xhr.send()
as the response, when it's not. If you want to parse the response you have to do it in the onreadystatechange
listener, using xhr.responseText
, like this:
xhr.onreadystatechange = function(){
alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
if(xhr.readyState == 4 && xhr.status == 200){
alert('Recogiendo respuesta...');
resp = xhr.responseText;
if(resp == false || resp == undefined){
alert('La lista de paises no se pudo obtener');
} else {
alert('La lista de paises se obtuvo correctamente');
console.log(resp);
var listaPaises = JSON.parse(resp);
}
}
}
Also, you cannot return the response since that the request is asynchronous, so you have to either do everything inside your function, or use a callback function, like this:
function loadCountries(cont, callback) { // use a callback
var i = 0;
var method = 'GET';
var path = appConstants.requestCountriesURL(cont);
console.log (path);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
if(xhr.readyState == 4 && xhr.status == 200){
alert('Recogiendo respuesta...');
resp = xhr.responseText;
if(resp == false || resp == undefined){
alert('La lista de paises no se pudo obtener');
callback(resp);
} else {
alert('La lista de paises se obtuvo correctamente');
console.log(resp);
var listaPaises = JSON.parse(resp);
callback(listaPaises);
}
}
}
xhr.open(method, path, false);
xhr.send();
}
// Create a callback
function myCallback(data) {
// Do what you want with the data...
}
// Call the function like this...
function loadCountries(myCont, myCallback);
Upvotes: 2