0

I want to put var inside var in javascript but don't know how.

this is my code

    var success;
   var fail;
    $.ajax({
        type:"POST",
        url:base_url+"/api/getDataCount",
        data: {error: true},
        async:true,
        dataType : 'JSON',
        success: function(data, status, xhr){
            success = data.count;
        },
        error: function(request, textStatus, errorThrown){
            console.log('Error retio bot');
        }
    }); 

$.ajax({
        type:"POST",
        url:base_url+"/api/getDataCount",
        data: {error: false},
        async:true,
        dataType : 'JSON',
        success: function(data, status, xhr){
            fail = data.count;
        },
        error: function(request, textStatus, errorThrown){
            console.log('Error retio bot');
        }
    }); 
    
      // Donut Chart
      var donutChartEl = document.querySelector('#donut-chart'),
        donutChartConfig = {
          chart: {
            height: 350,
            type: 'donut'
          },
          legend: {
            show: true,
            position: 'bottom'
          },
          labels: ['Success', 'Fail'],
          series: [success, fail],
    .......

I want to put success var inside donutChartEl var in the series. but I can't do that. is there anyone who know a better way for this. please help.

Qube
  • 543
  • 3
  • 9
  • 23
  • 1
    You mean you are getting chart data and you want to draw the chart in your view? What chart library are you using? – Jeremy Thille Jun 10 '21 at 09:46
  • You can move the code into the success function. –  Jun 10 '21 at 09:47
  • 1
    Aaaah no, I get it now, it's the good old [How do I return a response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) question :) – Jeremy Thille Jun 10 '21 at 09:49
  • I use apex chart @JeremyThille – Qube Jun 10 '21 at 09:51
  • I can't because I need to call one more ajax to fill the fail series @jabaa – Qube Jun 10 '21 at 09:52
  • Then why not just `success: function(data){ doSomethingElseWith(data) },` ? Simply pass your data along – Jeremy Thille Jun 10 '21 at 09:53
  • You have to find a way to trigger the code after you got the data. One "A" in AJAX stands for asynchronous. `success = data.count;` is evaluated after `var donutChartEl = document.querySelector('#donut-chart'), ...` –  Jun 10 '21 at 09:55
  • I already edit my code. actually I have 2 ajax call so I cant put donutChartEl var in only one of them – Qube Jun 10 '21 at 09:57
  • You should read the answers in the duplicate and Jeremy Thille's comment. I prefer the latter. You can create two promises and resolve them in the `success` functions. Combine both promises with [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) and trigger your your code. –  Jun 10 '21 at 09:59

0 Answers0