Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable from one Javascript to another Javascript file [duplicate]

Tags:

javascript

I tried the following, trying to pass a variable from one JavaScript file to another JavaScript variable. My first JavaScript file:

var x = "sachin";

My other JavaScript file can't access that x variable value. How do I solve this? I can access that x variable and same value in another file.

like image 933
Aravinth E Avatar asked Dec 21 '16 05:12

Aravinth E


People also ask

How do I pass data from one JavaScript to another?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

Can one JavaScript file reference another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How is a variable accessed from another file?

The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .


3 Answers

A variable in global scope can be access from all javascript file.
Your first js file

  //first.js file
    var globalVariable={
       x: 'sachin'
    };

And your second js file

    //second.js file
    alert(globalVariable.x);

And in html page add-

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 
like image 142
Ashvin Avatar answered Sep 21 '22 03:09

Ashvin


see about local and global variables for more info. http://www.w3schools.com/js/js_scope.asp.

Make sure your var X is not inside a function and that your file is load in the correct order.

<script src="file1.js"><script> //declare var x=1 here
<script src="file2.js"><script> // you can access x from here.
like image 34
chungtinhlakho Avatar answered Sep 19 '22 03:09

chungtinhlakho


I'm going to assume that you're running JavaScript in the browser. The order in which you include these files matters. If your script tags are in the wrong order, like...

<script src="file2.js"></script>
<script src="file1.js"></script>

If xis defined in file1, you can't use it in file2. file2 loads and runs first.

like image 38
bigblind Avatar answered Sep 22 '22 03:09

bigblind