access data from php to javascript - 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.

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.

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

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.

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.

Related

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

Save $.ajax response to variable (xml)

I'm trying to save the .ajax response, which queries a xml from a REST interface, but I am not successful. Until now the code works, and I get the response, but optimally I would like to parse some of the items into javascript variables or at least save the whole response into one variable. My code looks is the following:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
//Code Ends
Using console.log(data) I also can view the file as a document, but as already mentioned, I would like to save some XML-Elements into variables (or the whole XML document for a later processing).
The XML looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><osm generator="Overpass API" version="0.6">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2014-06-05T12:35:02Z"/>
<node id="1701218666" lat="41.8885564" lon="12.4950752">
<tag k="amenity" v="pub"/>
<tag k="name" v="Camden Town"/>
</node>
</osm>
Do you have any tips of how to proceed with my code snippets? I want to set the request to sync by using async: false
Thanks!
Create div tag in html body like and in jquery ajax part just use $(#result).append(data); inside sucess function
The response object you define within your success/error callbacks can be used as any other JS object. So if you have an existing variable you want to assign it to, do so (though try to avoid cluttering the global namespace) or even attach it to the page using jQuery's .data() function. Example:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
$('body').data('APIResult',data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
Then, elsewhere in your script, whenever you want to reference or use the API response, simply call it or assign it to a local var as such:
var APIData = $('body').data('APIResult');
foo = data
Note that foo will remain undefined until the asynchronous function has been resolved.
You should probably declare foo in the scope you want it in (using var foo outside the call to ajax).

How to access variable inside a block

I have an AJAX request:
var foo = [],
parse = '';
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
});
Now the string parse is the data that I want. How can I access that data? I tried showing it using alert(), but it's not displaying anything. I think this has to do with the variable scope.
How can I get that data?
parse looks like a global variable so it will be available anywhere. The issue is probably when you're trying to access it. You can ONLY access parse in your .done() handler or some function you call from that.
The reason for this is that your ajax call is asynchronous. That means that the operation starts, the rest of your javascript continues to execute and then SOMETIME LATER the ajax call completes and ONLY then is the parse variable valid. Because of this, there really is no reason to declare the parse variable the way you have. You should just use its value inside the .done() handler.
This is asynchronous programming and works differently than synchronous, sequential programming. You must use asynchronous programming techniques with asynchronous ajax calls.
If you try to access parse inside the .done() handler and it's still empty in there, then the issue is likely that data.item isn't what you think it is and maybe isn't triggering the .each() loop and thus nothing is getting put into foo or parse. To debug this case, you should look at what exactly is in data and data.item.
This would be my suggestion:
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
// no reason for these variables to be wider scope than here
var foo = [], parse;
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
// look at parse here
console.log(parse);
// if parse still empty, then look at data and data.item here
// to see what they are for debug reasons
console.log(data);
console.log(data.item);
// now, you can use parse here
callSomeFunction(parse);
});

maintain value of variable outside function in javascript?

I try to manipulate a variable inside a function. But it seems to forget the values once I exit the function, eventhough the variable is declared outside the function.
The essential code:
var posts = {};
// Perform a data request
// skjutsgruppens-page
$.oajax({
url: "https://graph.facebook.com/197214710347172/feed?limit=500",
*SNIP*
success: function(data) {
$.extend(posts, data);
}
});
// Gruppen
$.oajax({
url: "https://graph.facebook.com/2388163605/feed?limit=500",
*snip*
success: function(data) {
$.extend(posts, data);
}
});
The oajax retrievies data from facebook. I want to make a variable that contains the data from both oajax methods.
The actual code: http://eco.nolgren.se/demo/resihop/#
The issue is likely that the success function executes at an arbitrary time in the future--unless you specifically access posts after you know the success function has executed, you will receive undefined results, completely dependent on function and access timing.
The best approach is to handle this correctly by doing necessary work inside in the success function, or use something like jQuery's .when function.

Using Javascript / JQuery to access an array built from an external XML file

I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first piece of advice on here.
I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.
So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?
Here is my code...
Please help!!
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser
});
function do_xmlParser(xml)
{
var myArray = new Array();
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
console.log("inside "+myArray); // This outputs the array I am expecting
return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"
You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.
The way you have it now, the actual execution of code will go:
ajax -> file being requested -> console.log ->
file transfer done -> success handler
If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:
var myArray = [],
do_xmlParser = function (xml)
{
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
};
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser,
async: false
});
console.log("outside: " + myArray);
The async option doesn't work for cross-domain requests, though.
NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.
Edit:
Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).
look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.
console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.

Categories

Resources