Empty object array

Asked

Viewed 845 times

0

I have a problem creating an array of objects. I have a function that makes an ajax request and inserts objects inside an array in a looping.

It turns out that within the request Success, the array is shown in the console and through an alert in the right way, but outside the request 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 output

Within the request Success:

/*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 I proceed to solve this problem?

  • 1

    Ajax is asynchronous. When the script runs, when it reaches the.log console line from the outside, Ajax has not yet responded.

  • 2

    If you want to use the return of Ajax in some part of the code outside of Success, you must make a request to Ajax and wait for the answer. Using .then you can. Something like this answer: https://answall.com/a/281902/8063

  • Thanks for the answer. On console return, the values that returns from the two arrays are equal, except for one count as an array of one element. It wouldn’t just be the case in the array statement that something is incorrect?

  • 1

    I didn’t understand. From what I noticed is that the console.log inside the Success returns normal, 2 objects in the array, and outside it returns nothing []

  • In the console.log outside of Success it returns as if it were an empty array (in Alert JSON.stringify appears []), or an element, with the objects inside. Within Success, the.log console shows a 2-element array, and Alert JSON.stringify shows the objects within the array.

  • So that’s what I’m saying, this doesn’t work because Ajax is asynchronous. When you arrive at the.log console line outside of the Success, Ajax has not yet been processed.

  • But because the result of the request is already shown?

  • This result should be what is inside the Success.

  • Where I put 'Console.log' in the question, where it has /2/ corresponds to the result of the.log console outside of the Success and where you have it /1/ corresponds to the result within the Success. As shown there, ai ta printing on the console the result of the request, only the array ta with a different format.

  • The first is in string format, it seems to me, because it used JSON.stringify(arrayEvent)

  • Both Alert results are in Stringify. And the last code is the result of console.log in both cases.

  • This is the thing of the browser that will pull the updated array to show on the console, but in JS it is empty at that time

  • But note that even so it informs that it was empty at the time of execution with []

Show 8 more comments

1 answer

2

Basically the problem is that an http request is asynchronous, so the browser will go through the whole block of its javascript function, then go to the server.

Because of that the block below does not work.

    /*2*/alert(JSON.stringify(arrayEvent));
    /*2*/console.log(arrayEvent);

It is printing empty array as there is no server return yet. In order to happen what you want, the method must be used done, which will be executed when your ajax request is successfully executed.

Follow change in your code with the solution:

    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);
        }
    }).done(function(){
        /*2*/alert(JSON.stringify(arrayEvent));
        /*2*/console.log(arrayEvent);   
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.