Samuel Lopez
Samuel Lopez

Reputation: 2390

jQuery JSON response from j.post

I did not want to post this question since there are so many posts already about JSON parsing in jQuery, but I cannot seem to get it work. I have this select list that is populated by this JavaScript code. This is called from the HTML page onload:

function populateclienteslist () {
$.post('php/listaclientes.php', function(data){
data = JSON.parse(data);     
    if (typeof (data) == 'object' && JSON.parse ){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {      
    var d = data[i];
    if(!d.error){
    html += '<option value="' + (i+1) + '">' + d.cliente + '</option>';
}else{
    alert(d.error);
    }}
$('#clienteslist').append(html);}else{
    console.log("error");
    }
})
}

This works fine, and then when you select an item of the list the information of the list is displayed by this code, the function is called with the onchange;

function selectedcliente(){

var id_clientea = $('#clienteslist').val();
var jqxhr = $.post('php/selectcliente.php',{"id_cliente":id_clientea}, function(data){
data = JSON.parse(data)
if(typeof(data) == 'object' && JSON.parse){

var html = '';
var len = data.lenght;
for(var i = 0; i<len; i++){
var d = data[i];
    if(!d.error){
   html += d.contacto;
   d.contacto + '">'; 
    }else{
        document.write(data[i].error);  
        }

    }

    alert(html);
}else{
    alert("Is not object");

    }
    }
    )

}

Upvotes: 0

Views: 410

Answers (1)

Tieson T.
Tieson T.

Reputation: 21191

var len = data.lenght;

should be

var len = data.length;

EDIT: Sorry, forgot to mention that edit needs to be done in selectedcliente()

Upvotes: 1

Related Questions