Save $.ajax response to variable (xml) - javascript

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).

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.

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.
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.

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.

Calling a Javascript function after AJAX call

I have a javascript function to which I am being passed a functionName that I need to call after making a ajax call. The ajax call is returning some html that contains a reference to a js file. The functionName being passed to my function is in the html but it is referencing an object in the js file. What I am noticing that the object sometimes exists and sometimes doesn't. Is there a way to ensure that the object always exists(or wait till it exists) and then only call the javascript function. Please note that I have no idea what the object variable is, so is there a way to ensure that the script file has been loaded in dom and then make the call to the function.
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
// How to ensure that the script myfile.js is loaded in dom before I call eval
eval(functionName);
} );
}
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
//ensure the script has loaded.
$.getScript($('script:first',data).attr('src'), function(){
eval(functionName);
});
});
}
You can try to watch what is data before the ajax call end.
Not sure but, if data is "undefined" you can check something like this
var data = GetAjaxData();
while(typeof data === undefined);
bind, eval ecc ecc
But this will change if GetAjaxData return something else.
You can try the same thing but before do:
var data = null;
data = GetAjaxData();
while(data == null);
do stuff
You can also try $.ajax jquery with the success handler callback
Hope help

Getting rss feed with jquery and ajax

I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml&param=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"&param=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml&param=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle

Categories

Resources