-1

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.

pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • You can't. Put the usage code inside the callback. – Bergi Oct 05 '16 at 14:33
  • Duplicate? with the answer below I could do it, was a mistake on double defining the var. So it's not duplicate. – pmiranda Oct 05 '16 at 14:40
  • 1
    Oh, I overlooked the `async: false` you mixed in there. True, that doesn't make it a duplicate then, merely a typo. **However**, you *should* make this asynchronous and use the callback. Synchronous AJAX requests are a bad idea, as they're blocking your browser. – deceze Oct 05 '16 at 14:42

1 Answers1

0

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 }
Tushar
  • 3,022
  • 2
  • 26
  • 26
  • Thanks, I forgot to delete the "var" on the 2nd raw_data, because I wasn't defining it above in a previous version. – pmiranda Oct 05 '16 at 14:40