deeshank
deeshank

Reputation: 4486

access data from php to javascript

I intend to access set of records from MYSQL and handle it in Javascript for a calendar component. Hence I used PHP to fetch the records and dumped it as a array of json records to a flat file. Now i tried to read this json via flatfile from javascript but I am facing few issues.

var event_list;
$.getJSON("testFile.json", function(json) {
 alert("fetching");
 event_list= jQuery.extend(true, {}, json);
 alert(json);
 event_list=json;
 alert(JSON.stringify(event_list));   // This echo's me the data
 });
 alert(JSON.stringify(event_list));   // But this doesn't ???

I am unable to access the data outside the scope of getJSON() routine.

It would be great if someone could help me with this snippet.

Upvotes: 0

Views: 94

Answers (4)

Sivasailanathan
Sivasailanathan

Reputation: 135

You could make use of the async property and set to FALSE and global property to FALSE which would serve your requirements.

var data;
data= function () {
var tmp = null;
$.ajax({
    'async': false,
    'type': "POST",
    'global': false,
    'dataType': 'html',
    'url': "fetch_data.php",
    'data': { 'userid': "19"},
    'success': function (json) {
        tmp = json;
    }
});
return tmp;
}();

alert(data); //would give you the json data from PHP

Upvotes: 1

lazyCrab
lazyCrab

Reputation: 187

JQuery is using AJAX to load the JSON file, and AJAX is asynchronous.

Because of that what's happening is that the line after the getJSON is getting called first while the JSON file is still being loaded and the callback hasn't been called yet.

That's why event_list is still undefined and doesn't return any data.

Upvotes: 1

Halcyon
Halcyon

Reputation: 57721

You can't access the fetched JSON outside of the callback because it's bound to the scope of the callback, which may or may not be asynchronous (in this case, it is).

You can however hide the scoping by using Deferred (aka Promises/A).

jQuery has support for it like this:

var request = $.getJSON("testFile.json");
request.done(function (data) {
    console.log(data);
});

So now request is a promise that holds the value of your request.

There is no (good) way to make data available synchronously in the global scope.

Upvotes: 2

epascarello
epascarello

Reputation: 207557

Because it is an asynchronous call, not synchronous. The call outside is reading the variable before the Ajax call is made/returned. You need to do all of the work in the callback.

Upvotes: 1

Related Questions