pmirnd pmirnd - 1 month ago 7
JSON Question

acces to array outside an ajax call

I need to use the data from an array called struct, I'm calling the data from an ajax but then I don't know how to use it, look:

var raw_data = null;
$.ajax({
url:path.url_respuesta_leer, async:false,
type:"post", dataType:"json", data:{form:id},
success : function(obj) {
var raw_data = obj.struct;
}
//console.log(raw_data) show: [Object, Object, Object] 0:Object label:"Some text"
});

var new_data = [ {"Title": raw_data[0].label } , etc...


Console says that is undefined. I know it's simple, but I can't get it. Help please.

Answer

Don't refine that same variable again inside the ajax success block where you store the data.

var raw_data = null; // this should be only one.
$.ajax({
    url:path.url_respuesta_leer, async:false,
    type:"post", dataType:"json", data:{form:id},
    success : function(obj) {
        //var raw_data = obj.struct; don't use 'var'
        raw_data = obj.struct;
    }
    //console.log(raw_data) show: [Object, Object, Object] 0:Object label:"Some text"
});

var new_data = [ {"Title": raw_data[0].label }
Comments