-1

I have been already tired this code but I can access ajax response data in assets variable how can I access it.

const JSONURL = 'json';
var assets = {};

$(function() {
  $.ajax({
    url: `${JSONURL}/assets.json`,
    type: "GET",
    success: function(data) {
      assets.data
    }
  })
});

console.log(assets);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Nipu
  • 7
  • 6
  • 1
    Can you edit the question to be more clear. Neither the description or your code snippet make it obvious as to exactly what outcome you're trying to achieve – Rory McCrossan Jul 28 '19 at 18:52
  • I presume you meant `assets = data`, not `assets.data`? – Bergi Jul 28 '19 at 19:07
  • 1
    People are trying to help you understand that the statement `assets.data` does nothing, and that's true without regard to conducting an ajax operation. It's a do-nothing statement. – Pointy Jul 28 '19 at 19:25

2 Answers2

0

You can use Custom Event. In this case, on ajax success you want to fire a custom event. Think of it as an event, you define. In this case let's fire a custom event called my-first-fancy-custom-event on the window object. Then on the other hand you add the event listener (like any other event) but in this case you listen on the name you have defined, again it's my-first-fancy-custom-event.

window.addEventListener(
  "my-first-fancy-custom-event", 
  function(event) {
    // you will only need assets or event.detail
    // this is just to show both ways to get the data
    // chose one also in the ajax success method
    // my personal choice is to avoid global variables like assets
    console.log('assets: ', assets);
    console.log('event.detail: ', event.detail);
  }
);



const JSONURL = 'json';
var assets = {};

$(function() {
  $.ajax({
    url: `${JSONURL}/assets.json`,
    type: "GET",
    success: function(data) {
      // fire custom event here passing the data in detail object
      // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
      // for more details
      assets = data; // so either set the data to the global assets variable
      window.dispatchEvent(
        new CustomEvent(
          "my-first-fancy-custom-event",
          { detail: { myData: data } } // just add here and empty object => {}
                                       // if you chose global variable
        );
      );
    }
  })
});
caramba
  • 21,963
  • 19
  • 86
  • 127
0

if your api response is JSON then you need to just edit

success: function(data) {
      assets.data = data
    }

you can also bind assets object with window object for making assets to global scope