0

First, I would like to explain what I really want to do. I have some JS functions with ajax multiple times and also some functions. I want to place all such functions in a single place and make access form everywhere in my project. My first problem is that I cannot pass a ajax:success return into variables. Please guide me. My second problem is I tried some workaround and found that I cannot use a variable set in those functions. Other variables and functions are OK. Please check the codes and help me.

let result_data = null;
function ext_data(php_path, data_string){
    return{
        php_path,
        data_string,
        exec: function(callbaclFunc){
            let responseObject = null;
            $.ajax({
                url: this.php_path,
                type: 'POST',
                dataType: 'JSON',
                data: this.data_string,
                success: function(responseObject){
                    callbaclFunc(responseObject);
                }
            });
        }
    };
}//End of ext_data
function get_obd_data(){
    let data_string = cdc_check();
    if (data_string !== "false"){
        //let responseObject = null;
        let php_path = '../php/insert_update_delete_obd_data.php';
        let obd_data = ext_data(php_path, data_string);
        //obd_data.exec(function(fetch_data){console.log(fetch_data);});
        //result = obd_data.exec(function(fetch_data){return fetch_data;});
        obd_data.exec(fetch_data);
        console.log(result_data);
    }
}//End of get_obd_data()
function fetch_data(responseObject){
    //console.log(responseObject);
    result_data = responseObject;
    console.log(result_data);
}//End of fetch_data

If I check console, I receive result_data as null when I call from get_obd_data. When I check in fetch_data, all works OK. Please see the attached screenshot. Please help me.

console screedshot

taezar.tw
  • 63
  • 4
  • Are you familiar with the concept of modules and exports? – Algo7 Apr 21 '20 at 01:46
  • It works but you are logging too soon. If you wait until the result finishes then you should see it. Replace `obd_data.exec(fetch_data); console.log(result_data)` with `obd_data.exec(fetch_data); setTimeout(()=>console.log(result_data),2000)` to wait for 2 seconds to prove that the global variable is set – slebetman Apr 21 '20 at 01:49
  • The correct way to wait for `result_data` is to execute your code in the callback: `obd_data.exec((response) => {fetch_data(response); console.log(result_data)})`. Basically replace `fetch_data` with your actual code you want to execute – slebetman Apr 21 '20 at 01:50
  • slebetman - Thanks... – taezar.tw Apr 21 '20 at 03:28

0 Answers0