0

i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.

This works (async false):

function printTable(){
    var $table = $('#Table');

    var view_data;

    $.ajax({
        type: "GET",
        url: '/api/getdata',
        success: function(response) {

        var TableData = [];

        for(var i =0;i < response.length ;i++){
                    var item = response[i];

        var sessionID = item.sessionID;

                    if(sessionID){

                        $.ajax({
                        async: false,
                        type: "POST",
                        url: '/api/getNickname',
                        dataType: "json",
                        data: {
                        id: sessionID,
                        },
                        success: function(response){
                            view_data = response;
                        }
                     });

}

TableData.push({
                        _id: item._id,
                        datum: item.datum,
                        uhrzeit: item.uhrzeit,
                        session: view_data,
                        });

        }

        $table.bootstrapTable({data: TableData});
        $table.bootstrapTable('togglePagination');
            }   
    })
}

I tried the suggestion from here: Assigning ajax response to global variable without using async: false but it fails as view_data is undefined.

function printTable(){
    var $table = $('#Table');

    var view_data;

    $.ajax({
        type: "GET",
        url: '/api/getdata',
        success: function(response) {

        var TableData = [];

        for(var i =0;i < response.length ;i++){
                    var item = response[i];

        var sessionID = item.sessionID;

                    if(sessionID){

                    $.ajax({
                    type: "POST",
                    url: '/api/getNickname',
                    dataType: "json",
                    data: {
                    id: sessionID,
                    }
                 }).done(function(response){
                    test(response)
                 });

                 function test(response){
                     view_data = response;
                     return view_data;
                 }

            }

}

TableData.push({
                        _id: item._id,
                        datum: item.datum,
                        uhrzeit: item.uhrzeit,
                        session: view_data,
                        });

        }

        $table.bootstrapTable({data: TableData});
        $table.bootstrapTable('togglePagination');
            }   
    })
}

What i realized is if i put alert(view_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help.. How can i pass var view_data to the main function without using async false?

Thanks...

MaikelNight
  • 123
  • 2
  • 7
  • The code from the "main function" which uses the result of the ajax call should be placed in a callback. You should stop trying to "Return" values from functions that are async because it *doesn't work*. – James Jun 13 '19 at 12:22

2 Answers2

0

This has to do with asynchronous code

When you specify async: false, you are telling the code to wait until this HTTP call is completed.

But without async: false your http call is made asynchronously i.e. program will continue its execution without actually waiting for HTTP call to complete and your success function will only executed when HTTP call response is returned which will take 2 3 sec but you are accessing your view_data which is undefined at that time.

What you can do is move your push code inside the success function:

function printTable(){ var $table = $('#Table');

var view_data;

$.ajax({
    type: "GET",
    url: '/api/getdata',
    success: function(response) {

    var TableData = [];

    for(var i =0;i < response.length ;i++){
                var item = response[i];

    var sessionID = item.sessionID;

                if(sessionID){

                    $.ajax({
                    async: false,
                    type: "POST",
                    url: '/api/getNickname',
                    dataType: "json",
                    data: {
                    id: sessionID,
                    },
                    success: function(response){
                        view_data = response;
                        TableData.push({  // <- like this
                    _id: item._id,
                    datum: item.datum,
                    uhrzeit: item.uhrzeit,
                    session: view_data,
                    });
                   $table.bootstrapTable({data: TableData});
                   $table.bootstrapTable('togglePagination');


                    }
                 });

}

    }

        }   
})

}

asimhashmi
  • 4,258
  • 1
  • 14
  • 34
0

Here is the thing when JS is asynchronously, so when you use async: false, it means code the below code wont execute until you get respond. Declare variable(view_data) -> send asynchronously AJAX request(you dont wait for respond) -> below code excuted

Declare variable(view_data) -> send synchronously AJAX request(you wait for respond) -> assign respond to view_data -> below code excuted

so you write your j query into success after ajax request execute and you get respond

function printCatchTable() {
    var $table = $("#TableLastCaught");

    $.ajax({
        type: "GET",
        url: "/api/lastcaught",
        success: function(response) {
            var faengeTableData = [];

            for (var i = 0; i < response.length; i++) {
                var item = response[i];

                var sessionID = item.sessionID;

                if (sessionID) {
                    $.ajax({
                        type: "POST",
                        url: "/api/getSessionNickname",
                        dataType: "json",
                        data: {
                            id: sessionID
                        },
                        success: function(response) {
                            //Keep Pushing on Array
                            faengeTableData.push({
                                _id: item._id,
                                datum: item.datum,
                                uhrzeit: item.uhrzeit,
                                fischart: item.fischart,
                                gewicht: item.gewicht,
                                laenge: item.laenge,
                                koeder: item.koeder,
                                montage: item.montage,
                                gewaesser: item.gewaesser,
                                temperatur: item.temperatur,
                                luftdruck: item.luftdruck,
                                bilder: fileNames,
                                edit: item._id,
                                session: response
                            });

                            //run jquery on last element
                            if(i === response.length){//if i === response.length, it means its final element so you run jquery table
                                $table.bootstrapTable({ data: faengeTableData });
                                $table.bootstrapTable("togglePagination");
                            }
                        }
                    });
                }


            }
        }
    });
}

Markus Azer
  • 63
  • 1
  • 8