Rose
Rose

Reputation: 600

Storing result from FOR loop as one array (array only saves each results separately)

I have tried searching but can't find anything to help, maybe my problem is too simple! Anyway, I'm running an ajax request. The data given to the request is an array. Here is my code:

var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;
for (var i = 0; i < chkdLen; i++) {
    checkedId = arr[i];
    var checkedId = checkedId;
    var data = {};
    var year = $('#year').val();
    data["year"] = year;
    data['type'] = "report";
    data['accidentId'] = checkedId;
    console.log(data);
    ajax.readData('/report/readreport', data, null,
        function (result) {
            console.log(result);
        },
        function (error) {
            alert('err ' + error);
        }
    );

}

request array:

Object {year:"2015" type: "report", accidentId: "1"}
Object {year:"2015" type: "report", accidentId: "2"}
Object {year:"2015" type: "report", accidentId: "3"}
Object {year:"2015" type: "report", accidentId: "4"}
Object {year:"2015" type: "report", accidentId: "5"}

result:

{"data":[{"name":aaaa,"age":"15"}]}
{"data":[{"name":bbb,"age":"25"}]}
{"data":[{"name":ccc,"age":"65"}]}
{"data":[{"name":ddd,"age":"45"}]}
{"data":[{"name":eee,"age":"24"}]}

How to store the results in a single array?

Upvotes: 1

Views: 108

Answers (2)

Stefan Dimov
Stefan Dimov

Reputation: 591

Here is my Solution

var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
console.log(chkdId);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;

// here is the array
var arrayWithResults = [];

for (var i = 0; i < chkdLen; i++) {
    checkedId = arr[i];
    var checkedId = checkedId;
    var data = {};
    var year = $('#year').val();
    data["year"] = year;
    data['type'] = "report";
    data['accidentId'] = checkedId;
    console.log(data);
    ajax.readData('/report/readreport', data, null,
        function (result) {
            console.log(result);

            // here you push in the requested data
            arrayWithResults.push(result);
        },
        function (error) {
            alert('err ' + error);
        }
    );
}

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Take the ajax out of for. This will send only One ajax request to server and minimize the load on server.

var params = [];
for (var i = 0; i < chkdLen; i++) {
    checkedId = arr[i];
    var data = {};
    var year = $('#year').val();
    data["year"] = year;
    data['type'] = "report";
    data['accidentId'] = checkedId;


    params.push(data);
    // ^^^^^^^^^^^^^^
}

ajax.readData('/report/readreport', params, null,
//                                  ^^^^^^
    function (result) {
        console.log(result);
    },
    function (error) {
        alert('err ' + error);
    }
);

Upvotes: 0

Related Questions