0
$.ajax({
    url:"<?= site_url('laporan/data_penjualan/') ?>",
    type:'POST',
    dataType:'JSON',
    success:function(data){
      var abc = data;
    }
});

console.log(abc); // I want to use outside ajax

How I use data from db in outside ajax?

Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47
Aditya
  • 63
  • 7
  • 2
    Your answer is here [jquery-how-to-use-the-return-value-of-an-ajax-call-outside-that-ajax-call](https://stackoverflow.com/questions/9973681/jquery-how-to-use-the-return-value-of-an-ajax-call-outside-that-ajax-call) – Naim Malek Oct 26 '17 at 06:44

3 Answers3

1

You would have to either:

A. Use a promise object

function getData(){
    return new Promise((resolve, reject) => {
         $.ajax({
            url:"<?= site_url('laporan/data_penjualan/') ?>",
            type:'POST',
            dataType:'JSON',
            success:(data) => resolve(data)
        });
     };
}

getData().then(data => {
    //data is your ajax response
});

B. Use a callback function if your website supports browsers that don't support Promise and you don't have a polyfill

$.ajax({
    url:"<?= site_url('laporan/data_penjualan/') ?>",
    type:'POST',
    dataType:'JSON',
    success: function(data){
        ajaxComplete(data);
    }
});

function ajaxComplete(data){
    //data is your ajax response
}
Kevin F
  • 2,836
  • 2
  • 16
  • 21
0

you can set your var abc before ajax start, then set the val after finishing the ajax, but your console.log must using some way to call it after ajax finished because ajax is an asynchronous method.

var abc;
$.ajax({
    url:"<?= site_url('laporan/data_penjualan/') ?>",
    type:'POST',
    dataType:'JSON',
    success:function(data){
      abc = data;
    }
});

// call console when you know the abc has been set
console.log(abc);

// Example for waiting by setInterval
// var timer = setInterval(function() {
//    if(abc !== '') {
//       // your code
//       console.log(abc);
//       clearInterval(timer);    
//    }
// }, 1000); // change this to your liking, doesn't really matter
Stanley Cheung
  • 929
  • 7
  • 22
  • `console.log(abc);` will call before ajax response. So It's not usefull – Naim Malek Oct 26 '17 at 06:46
  • so I marked a comment for you to noticed that you need to call the console.log after ajax finished, otherwise you should use setInterval for waiting the ajax finished – Stanley Cheung Oct 26 '17 at 06:57
0

try this

var abc;
    $.ajax({
        url:"<?= site_url('laporan/data_penjualan/') ?>",
        type:'POST',
        async: false,
        dataType:'JSON',
        success:function(data){
        abc = data;
    }
});
console.log(abc);