0

I made my ajax request in synchronous mode not in asynchronous mode. Will this below code is okay? Will this cause any issue on the page?

Or else, Give me some idea how to make ajax request to store values in a variable.

var myPage = myPage || {};

myPage.datas = (function(){
var myvar='';
$.ajax({
async: false,
    type:'GET',
    url: 'JSON/carousel-data.json',
    dataType: "json",
    success: function(data) {
       myvar = data;   
    }
});
return myvar;
})();
User123
  • 453
  • 2
  • 6
  • 17
  • 7
    The page will be completely blocked during the ajax request.. so **bad idea** – Arun P Johny Mar 09 '15 at 12:21
  • 1
    How about using promises – Ramanathan Muthuraman Mar 09 '15 at 12:27
  • Could anyone please provide good idea as well on this? I am really looking for good idea.. – User123 Mar 09 '15 at 12:29
  • I wouldn't recommend to use *async:false*, as mentioned by Arun the browser will be blocked and there is no obvious reason to do synchronous calls in your above example. You may store values in the Window's scope i.e. `window.carouselData= data`, the created variable will remain until the browser is reloaded. – SaschaM78 Mar 09 '15 at 12:33
  • There is many examples here: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – A. Wolff Mar 09 '15 at 12:38

1 Answers1

0

a better, non ui-freezing, approach is:

var myPage = myPage || {};
myPage.loadData = function(onDataLoaded){
    var me = this;
    $.ajax({
        type:'GET',
        url: 'JSON/carousel-data.json',
        dataType: "json",
        success: function(data) {
            //set myPage.data
            myPage.data = data;
            onDataLoaded(data);
        }
    });
};
myPage.loadData(function(data){
    //do stuff with the data...
    //initialize your page or something
    // the data is set on myPage.data in the success callback
});

or you could use promises. It's basically the similar... here is a jQuery implementation:

var myPage = myPage || {};
$.when(
    $.ajax({
        type:'GET',
        url: 'JSON/carousel-data.json',
        dataType: "json"
    })
).done(function(result) {
    //the data is set on myPage.data
    myPage.data = result[0];

    //do stuff with the data...
    //initialize your page or something
});
VDP
  • 6,340
  • 4
  • 31
  • 53