1

Right now I have three files, two javascript files and one html file that will call upon these two javascript files. Inside my first javascript file, let's call it part1.js, I have this content:

var dataval;
$.get('example.cgi', function(data){
    dataval = data;
});

Inside part2.js, I am trying to call on this dataval value. But it is not working, as I am assuming that dataval is inside the get function and is therefore a local value. Is there anyway I can grab that value? My html file is calling on both of these javascripts. Is there anyway I can access that variable?

Thanks!!

JJJ
  • 32,902
  • 20
  • 89
  • 102
trynacode
  • 361
  • 1
  • 8
  • 18
  • What's inside of part2.js? Please specify every file content. – Mr.Web Jul 31 '15 at 21:49
  • 1
    `dataval` is most certainly not a "local" value in this case; only variables declared with a `var` keyword are in function scope. Your issue is because of the **A** in Ajax. – Dave Newton Jul 31 '15 at 21:50
  • Oh, I will check out that link Juhana. Hopefully my problem will be fixed! – trynacode Jul 31 '15 at 21:51

1 Answers1

2

There is a problem here with asynchronous calls. You should either use a callback function or make use of the jquery promise capability.

In your part1.js, you should instead define a function:

function callCgi(callback) {
    $.get('example.cgi', callback); //Callback will receive the data.
}

and then use it in part2.js:

callCgi(function(data) {
    //do something with data.
});

Or with promises:

function callCgi() {
    return $.get('example.cgi');
}

and then use it in part2.js:

callCgi().then(function(data) {
    //do something with data.
});
taxicala
  • 21,408
  • 7
  • 37
  • 66