0

How to assign value to global variable

function ok(){ 
    var idglobal; 

    $.get("<?php echo base_url('testchat/rtc/showchat'); ?>", function (data) {
        data = $.parseJSON(data);

        $.each(data, function (i, item) {
            idglobal = item.id;
        });
    });
}

console.log(idglobal);

above this code to assign value to global variable but the result is undefined

David Barker
  • 14,484
  • 3
  • 48
  • 77
Trisna
  • 385
  • 1
  • 5
  • 15

1 Answers1

0

You console.log isn't printing it because it runs before the promise resolves.

Try:

  function ok(){ 
   var idglobal; 
            $.get("<?php echo base_url('testchat/rtc/showchat'); ?>", function (data) {
                data = $.parseJSON(data);
                $.each(data, function (i, item) {
                    idglobal = item.id;
                });
                console.log(idglobal);
            });
            }

The value of idglobal should be the last item.id.

Bruno Garcia
  • 6,029
  • 3
  • 25
  • 38