0

How to make variable inside this post, Global? the console.log(BANK_NAME) returns values when its inside this POST function but outside that it says undefined? can anybody help me how to solve this?

var param={'id':$('#bankId').val()};
BANK_NAME;
$.post('<?php echo base_url(); ?>Employees/loadBankDataByID',param,function(data){
    // console.log(data);
    var obj=JSON.parse(data);
    obj=obj[0];

    var BANK_NAME = obj.BANK_NAME;
    console.log(BANK_NAME);  // it returns that value.
});
console.log(BANK_NAME);  // it say undefined here/
cks
  • 157
  • 1
  • 12
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Guillaume Georges Apr 30 '18 at 09:47
  • 1
    Your `BANK_NAME` variable is already global. The issue, here, is that `console.log(BANK_NAME);` is executed before your `$.post` call's response is treated. Read this for more informations on Ajax asynchronous calls : https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Guillaume Georges Apr 30 '18 at 09:51
  • [You can use promises too to handle ajax](https://api.jquery.com/jquery.when/) – Saad Suri Apr 30 '18 at 09:52

1 Answers1

2

This is happening because your POST request is asynchronous. In other words, it happens outside of the normal flow of (synchronous) code execution.

So it's a question of trying to open the letter before it's been delivered by the postman.

With AJAX you need to use callbacks that run when the request completes. You're sort of doing this already with some of the code. Just ensure ALL code that depends on the result of the request is in a callback.

//initiate the request
var req = $.post('<?php echo base_url(); ?>Employees/loadBankDataByID',param);

//log a callback to run after the request succeeds
req.done(function(data){
    var obj=JSON.parse(data);
    obj=obj[0];
    var BANK_NAME = obj.BANK_NAME;
    console.log(BANK_NAME);
});

//we can log multiple callbacks - anything that depends on the request should go in one
req.done(function() {
    alert('request complete!');
});
Mitya
  • 33,629
  • 9
  • 60
  • 107