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?

1

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You Very Much
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);

Comments

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

2 Comments

console.log(abc); will call before ajax response. So It's not usefull
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.