0

I have an AJAX that return some data. But, when I assigned the data to a new variable something goes weird. Only one data seems to be assigned. This is my AJAX.

var j1;
var j2;

$.ajax({
    url         : url_check,
    type        : 'POST',
    dataType    : 'json',
    data        : { tgl_book : val_date },          
    success     : function(data){
        alert(JSON.stringify(data));
        //{"MAX1":"10:00","MAX2":"11:00"}]

        j1 = data[0]['MAX1'];
        j2 = data[0]['MAX2'];
    }
});

alert(j1);
alert(j2);

When I run above script, only j2 has the data. The j1 is undefined.

ashura91
  • 441
  • 4
  • 17
  • Put your `alert`s inside the `success` function – JohanP Nov 08 '17 at 03:57
  • I'd like to use the variable outside AJAX. – ashura91 Nov 08 '17 at 03:58
  • I understand what you mean but using those variables outside of `success` does not make sense. Logically what you are saying is "when ajax call is successful, then execute some code that depends on `j1` and `j2` which is set from a successful response. – JohanP Nov 08 '17 at 04:02
  • I don't think this is a duplicate. The variables are being set asynchronously. `alert(JSON.stringify(data));` remove this line and see if it works. I believe that `alert` stops the execution of the scripts which may be causing this. You do want to use the variables outside but AJAX doesn't happen instantly as the code executes, it is asynchronous, you may consider wrapping the other alerts in a function like function alertFoo( data1, data2 ) { alert( data1 ); alert( data2 ); }, and then call `alertFoo` from within the `success` – Deepak Kamat Nov 08 '17 at 04:03
  • try to access j1 = gg[0].MAX1, j2 = gg[0].MAX2 – Casper Nov 08 '17 at 04:08
  • Thank you for all your response. It's solved. – ashura91 Nov 08 '17 at 06:13

0 Answers0