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.
Related
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
I have just started learning to code about 5 days ago and what I'm struggling to achieve, is to have an rssfeed-to-twitter script that posts a shortened url instead of a full website/article feed url. I found a node.js module called TinyURL that could do that but i struggle to get it to work. Here's the full script:
var simpleTwitter = require('simple-twitter');
var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end('RSS Twitter Bot\n');
}).listen(5693);
var timeInterval = 300000; // run every 30m
var timerVar = setInterval (function () {runBot()}, timeInterval);
function runBot(){
var lastCompleted = Date.parse(new Date(0));
console.log(lastCompleted);
try {
var lastcompletedData = fs.readFileSync('./lastCompleted.json', 'utf8');
var timeData = JSON.parse(lastcompletedData);
var lastCompletedFromFile = Date.parse(new Date(timeData.lastCompleted));
if ( isNaN(lastCompletedFromFile) == false ) {
lastCompleted = lastCompletedFromFile;
}
} catch (e) {
console.log(e);
}
fs.readFile('./config.json', 'utf8', function (err, data) {
if (err) console.log(err); // we'll not consider error handling for now
var configData = JSON.parse(data);
console.log(configData);
var twitter = new simpleTwitter( configData.consumerKey //consumer key from twitter api
, configData.consumerSecret //consumer secret key from twitter api
, configData.accessToken //access token from twitter api
, configData.accessTokenSecret //access token secret from twitter api
, 3600);
var dateNow = Date.parse(new Date());
var FeedParser = require('feedparser');
var request = require('request');
var req = request(configData.feedUrl);
var feedparser = new FeedParser();
req.on('error', function (error) {
console.log(error);
});
req.on('response', function (res){
var stream = this;
if (res.statusCode != 200 ) return this.emit('error', new Error('Bad status code'));
stream.pipe(feedparser);
});
feedparser.on('error', function(error) {
console.log(error);
});
feedparser.on('readable', function() {
var stream = this;
var meta = this.meta;
var item;
while (item = stream.read()) {
var itemDate = Date.parse(item.date);
//check to not publish older articles
if (itemDate > lastCompleted){
var titleLength = item.title.length;
var itemTitle = item.title;
var itemLink = item.link;
if (titleLength > 100) {
itemTitle = itemTitle.substring(0, 100);
}
twitter.post('statuses/update'
, {'status' : itemTitle + ' ' + itemLink + " " + configData.tags}
, function (error, data) {
console.dir(data);
});
console.log(itemTitle + ' ' + item.link + configData.tags);
}
}
//TO KNOW WHEN FROM TO START POSTING
var dateCompleted = new Date();
console.log('loop completed at ' + dateCompleted);
var outputData = {
lastCompleted : dateCompleted
}
var outputFilename = './lastCompleted.json';
fs.writeFile(outputFilename, JSON.stringify(outputData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
});
});
}
And this is the TinyURL node.js module
var TinyURL = require('tinyurl');
TinyURL.shorten('http://google.com', function(res) {
console.log(res); //Returns a tinyurl
});
Changing the 'http://google.com' string to itemLink var works just fine and prints it in the terminal as expected.
TinyURL.shorten(itemLink, function(res) {
console.log(res); //Returns a tinyurl
});
What i'm trying to achieve is:
twitter.post('statuses/update', {'status' : itemTitle + ' ' + tinyurlLink + " " + configData.tags}
How can i get the response turned into a e.g var tinyurlLink to replace the itemLink var? Any help would be much appreciated!
As suggested by #zerkms sending a tweet from inside the TinyURL.shorten worked!
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>
I have following two methods that uploads an image to a remote servlet. For some reason the second parameter which is the arraybuffer is not written to the post request and I am trying to figure out why this is happening. Could some one assist me on this.
setupBinaryMessage = function(metadata) {
log(metadata);
var msglen = metadata.length;
var localcanvas =document.getElementById("image");
var fullBuffer;
var myArray;
if(localcanvas){
var localcontext = localcanvas.getContext('2d');
//FOLLOWING 2 LINE OF CODE CONVERTS THE IMAGEDATA TO BINARY
var imagedata = localcontext.getImageData(0, 0, localcanvas.width, localcanvas.height);
var canvaspixelarray = imagedata.data;
var canvaspixellen = canvaspixelarray.length;
var msghead= msglen+"";
var fbuflen = msglen +canvaspixellen+msghead.length;
myArray = new ArrayBuffer(fbuflen);
fullBuffer = new Uint8Array(myArray);
for (var i=0; i< msghead.length; i++) {
fullBuffer[i] = msghead.charCodeAt(i);
}
for (var i=msglen+msghead.length;i<fbuflen;i++) {
fullBuffer[i] = canvaspixelarray[count];
count++;
};
return myArray;
} else
return null;
};
upladlImageWithPost= function() {
var message =JSON.stringify(this.data);
var fullBuffer = this.setupBinaryMessage(message);
var formdata = {command : "post", imagedata : fullBuffer,};
alert(jQuery.isPlainObject( formdata ));
var imgPostRequest = $.post( "http://localhost:8080/RestClient/RestClientPOST",fullBuffer, function(response) {
response = response.trim();
console.log(response);
if(response == "SERVER_READY"){
alert(response);
try {
}catch (error) {
alert("Web Socket Error "+error.message);
}
} else {
alert("SERVER ERROR");
}
}.bind(this))
Alright After some help from a GURU I figured the issue. Apparently ARRAYBUFFER is obsolete and real solution is to post the unisinged buffer as it is. But even for that I need to set the AJAX response type to ARRAYBUFFER and then not use JQuery $.post but
use original pure XHTTPRequest.
Source
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);
// ...
}