Callback hell help, writing a function inside a call back - javascript

I'm new to Javascript and trying to figure out how to properly write this.
$.get("https://localhost:8090/", function(response) {
console.log(response) #this works as expected
$.get("https://localhost:8090"+response), function() {
console.log('response') #nothing is printed
};
})
The response from $.get("https://localhost:8090/" is /oauth2callback. On my server (flask), I have logging enabled and I can see that the function inside the route is running properly.
The server code looks something like this:
#app.route('/oauth2callback')
def oauth2callback()
if 'code' not in flask.request.args:
logging.warning('code not in args')
auth_uri = flow.step1_get_authorize_url()
logging.warning(auth_uri)
return auth_uri
I can see in the log file that auth_uri is accurate.
However, I do not see console.log('response') being printed in my console. I assume this is due to my poor Javascript skills and not writing the callback correctly?
How should I structure this?
Thanks!

You have an extra ) by mistake
$.get("https://localhost:8090"+response), function() {
// ....................................^ remove this paren
}); // <--- and add it here

Related

writeFileSync doesn't callback

I am using writeFileSync function to write a file locally, the file does get written, however, the callback function is never called.
I did some googling, some other post are having the issue that it's either 1) passing the content went wrong or 2) having two write function at the same time.
My problem is that there are some other places in my code that is using the writeFileSync, but they are on different routes (not sure if this is the right terminology, localhost:port#/differentroutes <- something like this). I am testing only on my own route so those write functions shouldn't even be called.
Here is my code:
if(!fs.existsSync(dir)){
fs.mkdirSync(dir)
}
//content is just a string var I swear it's just a string
fs.writeFileSync('./pages/SubmissionProcess.html',content,function(err){
if(err){
throw err
}else {
console.log("YES")
}
})
I never see this "YES" nor error in my console even tho the file is already written....
Write file sync doesn't take a callback :D
Take a look at the documentation :
https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options
The parameters are (path, data, options)
If you want to check if the file actually wrote, you can read file sync after writing it or check the last time the file was updated. Otherwise, you should try using the async approach.
All of the synchronous methods throw rather than passing an error to a callback.
try {
fs.writeFileSync('./pages/SubmissionProcess.html', content);
console.log('YES');
} catch (e) {
console.error(e);
}

Javascript page not working when trying to get the ip address of the device opening the page [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am working on web ui project based on this project. Now what I want to do is that when a user opens the webpage, the ip address of the device from which this page is opened should be returned. For this I added the below code to the javascript` code here:
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
const ipInformation = JSON.parse(data);
console.log(ipInformation.ip);
return ipInformation.ip;
});
}
const sessionAttr = myIP();
I also added <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> at the top of the same javascript code file. Now sessionAttr constant is called at line 60 of this code file (Note that I changed sessionAttributes: config.lex.sessionAttributes to sessionAttributes: config.sessionAttr).
When I try to load this page nothing shows up. if I do not make changes I described above then the page loads up correctly. So somehow I am making some mistake in my additions which is screwing this page.
NOTE: I am not at all familiar with JavaScript but based on a quick search I made the changes described above. I understand the issue is in the asynchronous call I am making and I went through this suggested link but I am unable to figure out the right structure. Can anyone provide me the right syntax so that the page loads up correctly and also returns the ip address of the client and sets it to sessionAttribute?
UPDATE: After some suggestions I made following changes to my code (link here - https://jsfiddle.net/ywdeu0o4/3/)
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
$(document).ready(function(){
configDefault.Bot.sessionAttributes.ip = myIP();
// undefined
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
//console.log(data.ip);
return data.ip;
});
}
console.log("myVar:",configDefault.Bot.sessionAttributes.ip);
When I run this code after opening the console I get undefined value for configDefault.Bot.sessionAttributes.ip. Why is it coming as undefined and not the ip address?
Open the browser dev tool (F12). Very likely you will see an error in the console. For instance the data is already an object, no need to JSON.parse it.
Then there's the asynchronous nature of ajax as Mikael already pointed out. Use a callback function to do something with the data.
EDIT: there was already a link to a page explaining how to use a callback, but maybe it was too much to figure out. You should learn about variables, functions, variable scope, callbacks and async behavior.
Basically you could replace that return with code that updates your global object, and do stuff... or create a new function that you can call back:
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
$(document).ready(function() {
myIP();
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
// after succesful ajax response call myCallback with data.ip
myCallback(data.ip);
});
}
function myCallback(theIP) {
// do your stuff here
console.log("Data.ip:", theIP);
configDefault.Bot.sessionAttributes.ip = theIP;
console.log("ConfigDefault:", configDefault);
};
Example: https://jsfiddle.net/bvevqdb1/
You can also call the callback without passing parameters and without (). That would pass the whole ajax result to the callback, and you can then process it there:
https://jsfiddle.net/bvevqdb1/1/
This seems to work fine for me: https://jsfiddle.net/ywdeu0o4/1/
$(document).ready(function(){
myIP();
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
console.log(data.ip);
return data.ip;
});
}

Using a JS function defined in an included library, my success & error callbacks do not fire. Issue with my JS or theirs?

Relatively new to Javascript/Jquery!
tl;dr When I call a function (defined in an external library that I include), my success AND failure callback functions simply do not fire. Given my code below, is this an issue with my javascript or theirs?
I am using an external API along with it's Javascript library, which I include like so:
app/views/layouts/application.html.haml :
= javascript_include_tag 'application'
<script type="text/javascript" src="http://parcelstream.com/api/DmpApi.aspx?map=Bing&services=Utility&host=parcelstream.com/&v=4"></script>
My javascript, which is run on page load:
app/assets/javascripts/mine.js :
function GetByGeometry(point) {
function successCallback(json) {
console.log("success callback called");
// real code here, cut for brevity
}
function errorCallback(error) {
console.log("error callback called");
// real code here, cut for brevity
}
var url = "getByGeometry.aspx?returnGeoType=1&dataSource=SS.Base.Parcels/Parcels&Geo=" + point;
console.log("this is my query URL: " + url);
Dmp.Env.Connections["SS"].getJson(url, successCallback, errorCallback);
}
I am getting no feedback whatsoever. Neither successCallback nor errorCallback are ever fired off, and I am not getting an error either. What am I missing? Is this an error on my end, or is there something wrong with their .getJson() function?
Any insight would be greatly appreciated!
I don't have any clue about the Dmp.Env.Connections["SS"] object, so I cannot tell if that is working or not.
First thing to do is to look into the Network tab (under Developer Tools in Chrome) and check if an Ajax call is fired. This is will tell a lot - if a response is received from the server, if your payload is correct etc. I would start there, and then check for the API definition of Dmp.Env.Connections["SS"] and see if my arguments are correct.
Hope that helps.

console.log not printing the response

I have a function that calls another function over the server and returns a string back which i want to be printed in the browser's log windows, The function looks like:
function getErrorInfo() {
setTimeout(function () {
$.getJSON('Get/ErrorInfo', function (responseText) {
console.log("Log: "+responseText);
});
}, 5000);
}
getErrorInfo();
The function on the server sides does gets hits and returns a valid string But nothing is being displayed in the browser's windows Moreover the function on the server side must get hit after every 5 secs. but it only gets his on time and not again.
Please explain what am i doing wrong here.
Your basic issue is that you need to have properly formatted JSON in order to get back any result. Your result (per above) is:
3/8/2014 5:27:16 PMSystem.NullReferenceException: Object reference not set to an instance of an object. at movie.Models.Genre.GetPosts(Int32 min)
Not only is this an exception text, but it isn't valid JSON. JSON format is fully described here. Rather than calling a real service, I would recommend starting by just getting a static JSON file from the server. Then you know the data is correct.
Side Note:
The other issue here is how you print the OBJECT result from getJSON. When you try to print an object using "Console.log" it converts it to a string, which isn't probably going to show what you want. You should probably change your log statement to:
console.log(responseText);
In chrome at least, the console window will let you browse the contents of the object which can be really helpful. Between the note and the solution above I think you should have it. Best of luck!
When using $.getJSON(), the return result is required to be a valid JSON string, meaning it needs to be parsable into an object or array. In this situation, you can probably simply use $.get(), which will autodetect the return data type, or use $.ajax() and set the dataType: plain if you want to skip the JSON requirement.
On the second issue of keeping the log running, you can call getErrorInfo() from inside the setTimeout() or the callback, and it will keep running:
function getErrorInfo() {
setTimeout(function () {
$.getJSON('/echo/json/', function (responseText) {
console.log("Log: "+responseText);
getErrorInfo();
});
}, 5000);
}
getErrorInfo();
http://jsfiddle.net/Er5Lg/
In my opinion, in this situation, it is better than setInterval(), since that can get backed up and end up overriding calls, and the errors might display out of order.

Can't access the response variable from chrome.runtime.sendMessage. (Closure?)

I feel stupid because I've been trying to access this response variable for a while and I guess I do not understand closures or scope well enough, so please help.
I'm working on a chrome extension and I am sending a message from contentscript.js to background.js and receiving the response. Now I want to return the response and be able to use it in contentscript.js. Seems like something you should be able to do...
function getWords(){
var words = [];
chrome.runtime.sendMessage({detail: "words"}, function(response) {
console.log(response) // prints ["word1, "word2" ..]
words = response;
});
return words; // = []
}
UPDATE:
Thanks, I understand what my issue is now, but still would like some advice to solve it.
My question is what is the best way to "ask" the background page for a list of words if I need it immediately as a parameter in another function. Can I wait for the information to come back? Should I simply call that other function from the callback? or is there some other method?
Ideally I would like to actually implement a getWords() that doesn't return until the list comes back... Impossible? I'm open to open source libraries as well.
Because sendMessage is an asynchronous call and you are treating it as a synchronous one. You are trying to read words before the call is actually made. There is no way to wait for it. You need to use callbacks.
function getWords( callback ){
var words = [];
chrome.runtime.sendMessage({detail: "words"}, function(response) {
console.log(response) // prints ["word1, "word2" ..]
callback(response);
});
}
function processWords(words){
//do your logic in here
console.log(words);
}
getWords(processWords);

Categories