Second function with getJSON not executing - javascript

As the title says, I am trying to make a weather app which takes the users location and gets their local weather. I am stuck on the second function which will not execute and the console.log(); isn't providing any output. Any help would be greatly appreciated.
$(document).ready(function () {
function getLocation() {
$.getJSON("http://ipinfo.io", function (response) {
var cc = response.country;
var city = response.city;
var state = response.region;
$(".city").html(city + "," + state);
console.log(cc);
var url = "api.openweathermap.org/data/2.5/weather?q=" + city + "," + cc + "&APPID=1d0e324c03cd19ecf0abf20ac2708666";
console.log(city);
console.log(url);
getWeather(url);
});
}
function getWeather(url) {
$.getJSON(url, function (response) {
console.log(url);
$(".temp").html(Math.round(response.main.temp));
});
}
getLocation();
});

change the url in this way:
var url = "http://api.openweathermap.org/data/2.5/weather?q="+city+","+cc+"&APPID=1d0e324c03cd19ecf0abf20ac2708666";
you were missing http

URL for Weather API is incorrect, You need to use http:// with API otherwise its treated as relative URL.
Use
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + ...
function getLocation() {
$.getJSON("http://ipinfo.io", function(response) {
// console.log(response);
var cc = response.country;
var city = response.city;
var state = response.region;
//Updated the API
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + cc + "&APPID=1d0e324c03cd19ecf0abf20ac2708666";
getWeather(url);
});
}
function getWeather(url) {
$.getJSON(url, function(response) {
console.log(response);
});
}
getLocation();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Accessing the Forge Viewer From Two HTML Files

I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).

Console.log cannot show in jQuery

My javascript is using jQuery. However, when I clicked the #button_execute, the console.log in the callback function of .done didn't print anything on my console. I am not sure how can I console.log them.
$("#button_execute").click(function() {
var htmlContainer = htmlGraphContent();
var graphContext = returnGraphContext();
var formData = extractFormData();
var buildingId = formData.buildingId;
var zoneId = formData.zoneId;
var dateExtracted = formData.dateExtracted;
var url = "/api/building/" + buildingId + "/zone/" + zoneId + "/" + dateExtracted;
sendJqueryRequest("GET", url)
.done(function(data) {
console.log("#button_execute - data.data.result:",data.data.result);
buttonPlayLayout();
var resultArray = data.data.result;
htmlContainer.collapse("show");
lastDataRetrieved = resultArray;
console.log( "#button_execute_bms - sendJqueryRequest(\"GET\"," + url + ")");
startRealTimeGraph(resultArray, graphContext, formData);
console.log("real_time_graph.js - #button_execute_bms - lastDataRetrieved:",lastDataRetrieved);
})
.fail(function(error) {
alertCreator(error, "#bms-container", "bms-alert");
});
});
This is sendJqueryRequest
var sendJqueryRequest = function (type, url, data) {
var jsonToSend = {type: type, url: url};
console.log("sendJqueryRequest");
if(data) {
jsonToSend.data = data;
console.log("sendJqueryRequest jsonToSend: "+jsonToSend);
}
console.log(jsonToSend.url);
return $.ajax(jsonToSend);
};
Thanks.
I realised that's because of a really silly situation: I didn't realise that the console.log of front-end js will post to the console of the browser, not the console of the terminal. Sorry for wasting you guys so much time on this issue.

How to call in tag manager data after user OAUTH2 authorization is complete (JavaScript)?

I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent

How can I execute callback after multiple Ajax requests complete? [duplicate]

This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>
I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.
Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here
You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});

Node.js callback confusion

I am trying to implement an autocompleter on a nodejs app using nowjs.
everyone.now.sendAutocomplete = function(search) {
var response = getAutocomplete(search);
console.log("response");
console.log(response);
};
which calls:
function getAutocomplete(search) {
console.log(search);
var artist = new Array();
request({uri: 'http://musicbrainz.org/ws/2/artist/?query=' + search + '&limit=4', headers: "Musicbrainz Application Version 1"}, function(error, response, body) {
par.parseString(body, function(err, result) {
var count = result['artist-list']['#']['count'];
var artists = result['artist-list']['artist'];
// var artist = new Array();
if (count > 1) {
artists.forEach(function(a) {
var att = a['#'];
var id = att['id'];
var name = a['name'];
var dis = a['disambiguation'];
if (dis) {
var display = name + " (" + dis + " )";
} else {
display = name;
}
artist.push({'id':id, 'name': name, 'disambiguation':dis,
'label':display, 'value':name, 'category':"Artists"});
});
//everyone.now.receiveResponse(artist);
console.log("artist");
console.log(artist);
return artist;
} else {
console.log(artists);
var att = artists['#'];
var id = att['id'];
var name = artists['name'];
var dis = artists['disambiguation'];
var resp = [{'id':id, 'name': name, 'disambiguation':dis,
'label':name, 'value':name, 'category':"Artists"}];
return resp;
// everyone.now.receiveResponse([{'id':id, 'name': name, 'disambiguation':dis,
// 'label':name, 'value':name, 'category':"Artists"}]);
}
});
});
}
However, console.log(response) says that response is undefined. I am new to node so the answer is probably simple, but still can't figure it out.
You are treating the async call as synchronous. Your getAutocomplete needs to take a callback function to get the response. You're using that a lot already, in your request call and your parseString call.
Like this:
everyone.now.sendAutocomplete = function(search) {
getAutocomplete(search, function (response) {
console.log("response");
console.log(response);
});
};
And instead of return:
function getAutocomplete(search, callback) {
// ...
callback(result);
// ...
}

Categories