I have a problem creating an array of objects. I have a function that does an ajax request and inserts objects into an array in a loop.
It happens that within the success of the request, the array is shown in the console and through an alert the right way, but outside the request the alert appears as an empty array, [].
var arrayEvent = [];
$.ajax({
type : "POST",
url : http_base + "/agendamento/buscaProfessor",
data : {day:day, month:month, year:year},
cache : false,
dataType : "json",
success : function(data)
{
for (var i = 0; i < data.length; i++){
data[i].data = data[i].data.replace(" ", "T");
var obj = {title: String(data[i].professor), start: String(data[i].data)};
arrayEvent.push(obj);
}
/*1*/alert(JSON.stringify(arrayEvent));
/*1*/console.log(arrayEvent);
},
error : function(jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
/*2*/alert(JSON.stringify(arrayEvent));
/*2*/console.log(arrayEvent);
Array stringify alert result
Within the success of the requisition:
/*1*/[{"title":"Professor2","start":"2018-04-26T17:00:00"},{"title":"Professor
1","start":"2018-04-27T17:00:00"}]
Outside:
/*2*/[]
Console.log
/*2*/[]
0:{title: "Professor2", start: "2018-04-26T17:00:00"}
1:{title: "Professor 1", start: "2018-04-27T17:00:00"}
length : 2
/*1*/(2) [{…}, {…}]
0:{title: "Professor2", start: "2018-04-26T17:00:00"}
1:{title: "Professor 1", start: "2018-04-27T17:00:00"}
length:2
How could you proceed to solve this problem?