Handling Json data outside a function with pebble.js - ajax

In the function getweather() I do fetch some weather data from a Json-object and store that data in the variable data. Within that function, I can handle the Json-data, but how do I access the data from outside of getweather()?
It doesn't matter if i return the variable location or data. The variable place is just not Json.
How do I handle the place variable in order to make it work as it does within the function getweather()?
var ajax = require('ajax');
var place;
place = getweather();
function getweather()
{
// Make the request
ajax(
{
url: 'http://api.openweathermap.org/data/2.5/weather?q=paris.fr', type: 'json'
},
function(data)
{
// Success!
console.log("Successfully fetched weather data!");
// Extract data
var location = data.name;
return location;
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
}

The A in AJAX stands for asynchronous. What's happening in your code is that you are trying to assign a value to place before the asynchronous call to api.openweather.org has returned.
You can check this by placing a statement like console.log(place); directly after place = getweather();. You will notice in the console that None is returned before you see Successfully fetched weather data!
This issue has been described in detail in this post. It recommends restructuring your code around your callbacks.

Related

using data in dynamodb

I am querying a dynamodb table and i am getting the results required, however i cant seem to figure out how to pass the results for use.
I haven't included the params array but its standard. This code lives inside of a lambda.
What im trying to achieve is to make this update the "value" parameter with the contents of "item[0]['the_data'];
var value = "not changed after the dbase query, why?";
dynamodb.query(queryparams, function(err, data) {
if (err) {
console.log("Query Error", err);
} else {
if(data.Count > 0){
var item = data.Items;
value = item[0]['the_data'];
//console.log("The data: " + JSON.stringify(item));
}
}
});
Yes,
It’s shows in CloudWatch, and the log when I use the test functionality in the lambda itself.
The only way around it so far has been to create an s3 object, and creating another gateway and function to return that objects content.

Angular $http returning new values only once

I am new to Angular, and set up a simple example with a REST Api config in Codeigniter that returns a json (default) thread list. No problems!
Until, I add an update to the Database. If I clear/then call getThreads again, I receive the same list of items. A page refresh solves this. I can see in firebug that its only calling the url:api/example/threadlist/id/'x' once per page load.
function ThreadsCtrl($scope, $http, $templateCache) {
$scope.getThreads = function(id) {
if (!id) { id = 'reset'; }
$http({method: 'GET', url: 'api/example/threadlist/id/' + id, cache: $templateCache}).
success(function(data) {
$scope.threadslist = data; //set view model
}).
error(function(data) {
$scope.threadslist = data || "Request failed";
});
};
How would I make it so that it always calls a new list of data rather than reuses the old.
Thanks!
If i understood your question correctly your ajax call is being cached so you have to remove cache:$templatecache from your code

Filtering a loaded kml file in OpenLayers

I'm trying to create an interactive search engine (for finding event tickets) of which one of its features is a visual map that shows related venues using OpenLayers. I have a plethora of venues (3000+) in a kml file that I would like to selectively show a filtered subsection of. Below is the code I have but when I try to run it has a JavaScript error. Running firebug and chrome developer tools makes me think that it is not getting passed the parameters I give because it says that the variables are null. However, I cannot figure out why they are not getting passed. Any insight is greatly appreciated.
var map, drawControls, selectControl, selectedFeature, select;
$('#kml').load('venuesComplete.kml');
kml=$('#kml').html();
function showVenues(state, city, venue){
filterStrategy = new OpenLayers.Strategy.Filter({});
var kmllayer = new OpenLayers.Layer.Vector("KML", {
strategies: [filterStrategy,
new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "venuesComplete.kml",
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true
})
})
});
select = new OpenLayers.Control.SelectFeature(kmllayer);
kmllayer.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
});
map.addControl(select);
select.activate();
filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "",
value: ""
});
function clearFilter(){
filterStrategy.setFilter(null);
}
function setFilter(property, value){
filter.value = value;
filter.property = property;
filterStrategy.setFilter(filter);
}
var vector_style = new OpenLayers.Style();
if(venue!=""){
setFilter('name', venue);
}else if(city!=""){
setFilter('description', city);
}else if(state!=""){
setFilter('description', state);
}
map.addLayer(kmllayer);
function onPopupClose(evt) {
select.unselectAll();
}
function onFeatureSelect(event) {
var feature = event.feature;
var selectedFeature = feature;
var popup = new OpenLayers.Popup.FramedCloud("chicken",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
"<h2>"+feature.attributes.name + "</h2>" + feature.attributes.description +'<br>'+feature.attributes,
null,
true,
onPopupClose
);
document.getElementById('venueName').value=feature.attributes.name;
document.getElementById("output").innerHTML=event.feature.id;
feature.popup = popup;
map.addPopup(popup);
}
function onFeatureUnselect(event) {
var feature = event.feature;
if(feature.popup) {
map.removePopup(feature.popup);
feature.popup.destroy();
delete feature.popup;
}
}
}
function init() {
map = new OpenLayers.Map('map');
var google_map_layer = new OpenLayers.Layer.Google(
'Google Map Layer',
{type: google.maps.MapTypeId.HYBRID}
);
map.addLayer(google_map_layer);
state="";
state+=document.getElementById('stateProvDesc').value;
city="";
city+=document.getElementById('cityZip').value;
venue="";
venue+=document.getElementById('venueName').value;
showVenues(state,city,'Michie Stadium');
map.addControl(new OpenLayers.Control.LayerSwitcher({}));
map.zoomToMaxExtent();
}
IF I UNDERSTAND CORRECTLY, your kml does not load properly. if this is not the case, please disconsider my answer.
it is very important to check if your kml layer was properly loaded. i have a map that loads multiple dynamic (from php) kml layers and it is not uncommon to have a large layer simply not load. when that happens, the operation is aborted, but, as far as openlayers is concerned, the layer was properly loaded.
so i do 2 things: i check if the amount of loaded data meets the expected number of features in my orginal php kml parser (i use a jquery or ajax call for that) and then, in case there is a discrepancy, i try reloading (since this is a loop, i limit it to 5 attempts, so as not to loop infinitely).
check out some of my code here

Should i use threads when executing action method through AJAX?

I am building a questionnarie. When a user clicks on an answer possibility for a multiple choice question (this is a radio button), i call an action method to save this answer.
The code:
<script language="javascript">
$(document).ready(function () {
$('.MCQRadio').click(function () {
var question_id = $(this).attr('question-id');
var mcq_id = $(this).attr('mcq-id');
$.ajax({
url: '/SaveSurveyAnswers/SaveMCQAnswer',
data: { "mcq_id": mcq_id, "question_id": question_id },
success: function (data) {
}
});
});
});
The code to save the answer:
public EmptyResult SaveMCQAnswer(int mcq_id, int question_id)
{
MCQ_Answers mcqa = null;
try
{
mcqa = db.MCQ_Answers.Single(x => x.question_ID == question_id);
}
catch (InvalidOperationException e)
{
}
if (mcqa != null)
{
mcqa.mcq_id = mcq_id;
}
else
{
MCQ_Answers mcq_answer = new MCQ_Answers()
{
question_ID = question_id,
respondent_id = 1
};
db.MCQ_Answers.AddObject(mcq_answer);
}
db.SaveChanges();
return new EmptyResult();
}
If a question has 5 answer possibilities, and i click on them randomly and fast, and then go back to the previous page, ie, when i return the correct answer wont be saved. Should i use threading to make sure the correct answer is saved? And how?
Thanks
rather than saving your answer by post all the time, you can just create a JSOn object and save the answers within json. you can then at the end post all completed answers in one go.
take a look at this: http://msdn.microsoft.com/en-us/scriptjunkie/ff962533
basically this will allow you to store session data - json on the remote machine you then just need an add, delete function and away you go....
i use this to huge extent in an application that would require the server to be updated with the location of objects on a canvas, however with sessvars i just keep all the X and Y locations within there and do a final push of JSON when i am done.
if you change pages, you can then get your values from the JSON object without a server call.
as a note you may also be better off with tabs or hiden sections of form, and therfor reduce the need to re-populate say page1, page2 etc as they will already be there, just hidden!

How can I pass parameters with callback functions to search APIs like Yahoo BOSS and BING?

I am using Yahoo BOSS and Bing APIs to provide search functionality to my site. Specificaly, I use their JSON response formats where I would pass a callback function to the search provider that would later be called back with the search results. My callback function actually gets called, but the problem is, if I make more than one requests at a time, I can't tell which request a certain response is for. To this end, is there a way to pass additional parameters with the callback function to the search provider so that I can later use it to identify which response goes with which request?
Thank you
I have a same problem with you! I googled and find some solutions
and I has solve my problem. Now i show it to you, I hope it can help you :)
Previous code:
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d
$.each(pins, function (index, pin) {
var geocodeRequest = 'http://ecn.dev.virtualearth.net/REST/v1/Locations/' + pin.City + ',' + pin.Country + '?output=json&jsonp=GeocodeCallback&key=' + credentials;
CallRestService(geocodeRequest);
});
function CallRestService(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
function GeocodeCallback(result) {.. to do with result callback, --> i want to add some pin infomation here}
Because each sccipt when add to document ( document.body.appendChild(script);) it will be run --> and callback, you cant add more params.
I solve it by request through ajax (doesnt add to document any more), when the ajax call success --> I call the GeocodeCallback(result, pin)
Here is the complete code.
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d;
$.each(pins, function (index, pin) {
$.ajax({
url:"http://ecn.dev.virtualearth.net/REST/v1/Locations/",
dataType: "jsonp",
data:{key:credentials,q:pin.City + ',' + pin.Country},
jsonp:"jsonp",
success: function(result){
GeocodeCallback(result,pin);
}
});
});
}
function GeocodeCallback(result,pin) { ... to do here}

Resources