Get the variable of a json request outside the function (jquery) - ajax

I feel pretty stupid asking this but how can I get the variable crdnts outside the function
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
//alert(crdnts);//this works
return crdnts;
});
}
};
alert(coordinates.LoadDefault());//I would like to get the crdnts variable here.
});
or
http://jsfiddle.net/stofke/Lv3YD/

javascript ajax is asynchronous. so you need to use callbacks:
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
call_alert(crdnts); //callback
});
}
};
function call_alert(cr){
alert(cr);
}
coordinates.LoadDefault();
});

You can't. Your Ajax call is asynchronous, so you cannot predict when will it return.
The only thing you can do is doing something with it in the success callback, or set your Ajax to be synchronous if it is a choice (in this case all JS execution will wait until the request is finished).
For example, you can call a function when the Ajax call successfully finished:
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
callSomething(crdnts);
});
}
};
function callSomething(x) {
alert(x);
}
});

Related

Leaflet mapping: Assign object to fetch promise for local GeoJSON file

I am looking to assign as an object a Fetch API promise from a local GeoJSON file.
Here is the code
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites
}).addTo(map);
});
};
I tried the call back method, as advised here
Saving fetched JSON into variable
(EDIT) New code, but there is still a missing formal parameter
function getData("data/sites.geojson", cb) {
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function (feature, layer) {
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
.then(function(result) {
cb(result);
});
});
};
getData("data/sites.geojson", function (data) {
return console.log({data});
});
Most probably just incorrect syntax of your callback function:
// Use either arrow function
getData("data/sites.geojson", (data) => {
return console.log({data});
});
// or standard function
getData("data/sites.geojson", function (data) {
return console.log({data});
});
I found the way to work this out by adding within the fetch function, what I originally wanted to do on the map.
This was to add a L.controlLayer using the geojson as overlay.
This is the code that made it work:
let sites = getData()
.then((function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function LayerControl(feature, layer) {
var popupText = "<b>" + feature.properties.nombre + "<br>";
layer.bindPopup(popupText);
category = feature.properties.tipo;
// Initialize the category array if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = L.layerGroup().addTo(map);
layersControl.addOverlay(categories[category], category);
}
categories[category].addLayer(layer);
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
}));
Actually it comes from one of your answer on another post ghybs.

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

How to make wrapped jQuery promise fire the reject callback on error?

I'm wrapping a simple jQuery promise with RSVP and noticed that when I cause an error on purpose the failure callback is never invoked. I assume it's because when you use vanilla jQuery and the callback throws an error, the returned promise will not be moved to failed state (the opposite of the spec).
If I need to use jQuery $.ajax but I want to get true resolve/reject callbacks with RSVP what (if anything) can I do to the example below?
var peoplePromise = new Ember.RSVP.Promise(function(resolve, reject) {
$.getJSON('/api/people/', resolve).fail(reject).error(reject);
});
var catPromise = new Ember.RSVP.Promise(function(resolve, reject) {
$.getJSON('/api/cats/', resolve).fail(reject).error(reject);
});
Ember.RSVP.all([peoplePromise, catPromise]).then(function(things) {
things[0].forEach(function(hash) {
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
things[1].forEach(function(hash) {
var wat = hash.toJSON(); //this blows up
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
}, function(value) {
alert(value.status + ": promise failed " + value.responseText);
});
Example here: http://www.youtube.com/watch?feature=player_detailpage&v=g5CSaK3HqVA#t=1080
var ajaxPromise = function(url, options){
return Ember.RSVP.Promise(function(resolve, reject) {
var options = options || {};
options.success = function(data){
resolve(data);
};
options.error = function(jqXHR, status, error){
reject([jqXHR, status, error]);
};
$.ajax(url, options);
});
};
var peoplePromise = ajaxPromise('/api/people/',{
dataType: "json"
});
var catPromise = ajaxPromise('/api/cats/',{
dataType: "json"
});
Ember.RSVP.all([peoplePromise, catPromise]).then(function(things) {
things[0].forEach(function(hash) {
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
things[1].forEach(function(hash) {
var wat = hash.toJSON(); //this blows up
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
}, function(args) {
var jqXHR = args[0];
alert(jqXHR.status + ": promise failed " + jqXHR.responseText);
});
http://emberjs.jsbin.com/aREDaJa/1/

Jasmine calling function with ajax returned value

I want to test the "addGroup" function using Jasmine. I get the following error:
Error: Expected spy modifyMyHtml to have been called.at null.
I don't know what is the best way to test the addGroup function. Please HELP.....
var myRecord = {
addGroup: function(groupNumber) {
$.when(myRecord.getHtml())
.done(function(returnedHtml){
myRecord.modifyMyHtml(returnedHtml);
});
},
getHtml: function() {
return $.ajax({url: "myHtmlFile.html", dataType: "html" });
},
// adds options and events to my returned HTML
modifyMyHtml: function(returnedHtml) {
$('#outerDiv').html(returnedHtml);
var myOptions = myRecord.getOptions();
$('#optionsField').append(myOptions);
myRecord.bindEventsToDiv();
},
}
====JASMINE TEST
describe("Configure Record page", function() {
var fixture;
jasmine.getFixtures().fixturesPath = "/test/" ;
jasmine.getFixtures().load("myHtmlFile.html");
fixture = $("#jasmine-fixtures").html();
describe("addGroup", function(){
beforeEach(function() {
var groupNumber = 0;
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().promise();
});
spyOn(myRecord, "modifyMyHtml");
myRecord.addGroup(groupNumber);
});
it("Should call getHtml", function() {
expect(myRecord.getHtml).toHaveBeenCalled();
});
it("Should call modifyMyHtml", function() {
expect(myRecord.modifyMyHtml).toHaveBeenCalled(); ==>FAILS
});
});
});
You have to resolve the promise before you return em in your andCallFake.
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolve ().promise();
});
Btw. you should not test that the function on the object you wanna test are called, but that the html in the DOM are set with the right html
it("Should call modifyMyHtml", function() {
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolveWith(null, 'returnedHtml').promise();
});
expect($('#outerDiv').html).toEqual('returnedHtml')
});

Node JS - get file via AJAX and then use the data

How do I do this asynchronously?
var getData, myFunc;
getData = function() {
var data = "";
$.get("http://somewhere.com/data.xml", function(d) {
data = $("#selector", d).html();
});
return data; // does not work, because async callback not yet fired
};
myFunc = function() {
var data = getData();
// do something with data here
};
I am happy to completely re-factor to achieve what I want. I am just don't know what design pattern achieves this.
Well, you can't. You can return a promise though:
var getData, myFunc;
getData = function () {
var d = $.Deferred();
$.get("http://somewhere.com/data.xml", function (data) {
d.resolve($("#selector", data).html())
});
return d.promise();
};
getData().then(function (data) {
alert(data);
});
demo http://jsfiddle.net/W75Kt/2/

Resources