Solar
Solar

Reputation: 1015

How to pass an external JSON file into a javascript variable that can be accessible anywhere

I have a json file which I have been using in my project in this structure

<script src="js/main.js"></script>

<script>    
    var data = {"bills":[{"id":1,"name":"DStv","reference":"SmartCard Number","logo":"bill\/logo\/24Io6IqObQ8ddi5.jpg","active":1,"lifestyle":0},{"id":3,"name":"GOtv","reference":"IUC Number","logo":"bill\/logo\/mCNl5X1ZCfph4kg.jpg","active":1,"lifestyle":0},{"id":6,"name":"Startimes"...
</script>

<script src="js/bill.js"></script>
<script src="js/airtime.js"></script>

As you can see from the above example, the json file have already been passed to a data variable... of which I have other external javascript file placed under it.

Meanwhile, the json file is now generated/accessible from a link and I was told to use ajax to get the json data into the project.

I have this code in my main.js file, I have the below code but its not accessible in the bills.js file

$(document).ready(function () {

   $.ajax({
       type: "GET",
       url: "http://example.com/bills/resources",
       success: function(result)
       {
           data = result;
           loadData(result);

       }
   });

});

Upvotes: 4

Views: 328

Answers (2)

Basil Battikhi
Basil Battikhi

Reputation: 2668

if it is a static variable and pulled just once then you can use Javascript cookie instead of creating global variable in the same file in order to get the value where ever you need

 $.ajax({
       type: "GET",
       url: "http://bills.payit.ng/bills/resources",
       success: function(result)
       {
           data = result;
           setCookie("myStaticDataPerDay",data,1)
           loadData(result);

       }
   });
});

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

and you should be able to retrieve it by

console.log(getCookie("myStaticDataPerDay"));
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Also you can save it in jquery cookie

$.ajax({
       type: "GET",
       url: "http://bills.payit.ng/bills/resources",
       success: function(result)
       {
           data = result;
           $.cookie('myStaticData', data);
           loadData(result);

       }
   });
});

and you will need to get the value by

var data=JSON.parse($.cookie("MyStaticData"))

Update You can also use localStorage in case if you have IOS users because ios doesn't accept cookie

Upvotes: 1

Fawaz
Fawaz

Reputation: 3560

You can use events to pass data :

// in ajax success
var event = new CustomEvent("custom-event", {data: result});
window.dispatchEvent(event);

and then in your bill.js script or any place you need the data :

window.addEventListener("custom-event", function(e) {
  console.log("custom-event", e.data);
});

Upvotes: 0

Related Questions