0

I have an AJAX function that gets JSON response. I want to convert this JSON repsonse into a global object using prototype. I don't have a clear concept of prototyping but I think my idea is correct. Forgive me if I am wrong.

Here is the code

var RatesGlobal = {};

$('#tarrif').load("<?php echo base_url(); ?>index.php/rates/index", function (data) {

    RatesGlobal.prototype.tarrifRates = JSON.parse(data);

});    

I want to later access the values of the JSON string, forgive me if the question is not clear enough. I don't know if this is the proper usage of prototypes. What is the right way of doing so ?

Bazinga777
  • 5,140
  • 13
  • 53
  • 92
  • 1
    No, my question is not about the response but creating a global object or a variable from the response. – Bazinga777 Mar 17 '14 at 18:51
  • @Bazinga777 Then simplify the code such that there is no unnecessary `load` involved. The introduction of `load` *only* affects the [a]synchronous nature. – user2864740 Mar 17 '14 at 18:51
  • It doesn't really look like you're getting it? You're using `load()` to fetch JSON, and then for some strange reason you'd like to get that JSON, parse it, and have a global? For what purpose? You know you can't use the JSON until the ajax request is done, and that `load()` inserts content automagically in your HTML ? – adeneo Mar 17 '14 at 18:54
  • Sorry, my mistake in using load, my idea was to create a global object using AJAX. Poor questioning on my part but @Minkos answer is what I was looking for. – Bazinga777 Mar 17 '14 at 18:58

1 Answers1

0

You don't need any prototype. Prototypes are usually used for code reuse.

Use:

$('#tarrif').load("<?php echo base_url(); ?>index.php/rates/index", function (data) {
    window.GLOBAL = JSON.parse(data);
});

Access it this way: window.GLOBAL.

You can create object, which prototype is the response of your request:

$('#tarrif').load("<?php echo base_url(); ?>index.php/rates/index", function (data) {
    window.GLOBAL = Object.create(JSON.parse(data));
});

Anyway, I don't see why you would ever need this.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68