wait for chrome.extension.sendRequest - javascript

I want to read my global variable from background.html , and I use this:
chrome.extension.sendRequest()
I run this code in my timer function... and everytime it return me undefined. If I put a alert message in above function then it show me my variable.. if I'm not using alert() then it is undefined. So how can I wait above function to return correct value,... as I understand I need to wait for response... but how can I do it right, I tried to use setInterval inside above function and not help me.
How can I read my global value from background.html... I need a piece of code.
chrome.extension.sendRequest({cmd: "myvalue"}, function(response) {
myglobalvalue = response;
if(response==1){
alert("response: "+response); // alert show me right value
}
});
if(myglobalvalue)doFunc(); //myglobalvalue is undefenited

You can read variables from background.html with chrome.extension.getBackgroundPage().varname

chrome.extension.sendRequest accepts a callback function that will fire with the response data.
chrome.extension.sendRequest({ data: 'send data' }, function(response) {
console.log(response);
// the var has been returned and you can use it here or call another function.
});

Here you go: Chrome Extension Socket
I build this to provide continuous 2 way communication between a popup and background page. The "How To Use" section tell you what to do. Just include socket.js in your popup and background page, the connection will be created automatically for you.
Just use:
Socket.postMessage(namespace, literal, method, [args]);
This will allow you to trigger functions that can callback with data.

Related

document.ready() just running one function instead of two

I'm trying to run two js functions(i'm using jquery) in the document.ready(), but only runs one. Here is my code:
$(document).ready(function() {
show_properties();
table_events();
});
the functions are written in the same js file, but only show_properties() is loaded when the website loads. I tested in the firebug console to write
table_events()
and the console tells me "undefined", but after that the function gets loaded and the ajax calls and everything inside that function starts to work.
Why is that? How can I fix this behavior?
thanks.
Here are the functions I want to run:
function table_events(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
}
function show_properties(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('#busca_propiedades').on('click',function(){
var user_id = $('#user_list').val();
/*var data = $.ajax({
url: "properties_list.php",
type: 'POST',
data:{ 'user_id': user_id },
cache: false,
async: false
}).responseText;
});*/
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id});
//alert(data);
});
}
EDIT:
after some debugging with console.log , i found out that this code is the one that's not executing when the webpage loads:
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
apparently, this function() is the one that doesn't run when the webpage loads; but when I write again in the console
table_events()
THEN the code inside this function runs when I click in the tr of the table.
Are $('.apartamentos tr') elements loaded with the load call in show_properties?
If yes then the problem is due to the fact that when table_events is executed, tr elements are not yet inserted in the #lista_aptos (cause load uses ajax, that's asynchronous).
To check please add
console.log("trs count: ", $('.apartamentos tr').size());
on top of your table_events function.
To fix you should pass table_events as completetion handler to load call:
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id}, table_events);
Old response
You said "...after that the function gets loaded and the ajax calls..."
Keep in mind that ajax calls are asynchronous.
If you define the table_events function inside the ajax response handler, also if you do something to put it in a scope visible from the referencing function, the attempt to call table_events may occur before the table_events definition.
or, as Raghavan says, there's an error thrown from show_properties that prevents the execution of table_events. But better if you try to debug with console.log("text") instead of alert (alert is blocking and it will hide you problems from asynchronous calls)
please, try to make a example on http://jsfiddle.net/
If the console returns "undefined" that means the function exists, but it's returning undefined as a result.
Your function needs fixing, $(document).ready() is probably fine.
Try calling table_events() at the last line in show_properties() and see if that works.
A few things to check:
Does table_events exist in the scope of $(document).ready?
Is show_properties possibly raising an error?
This may be a good case for "alert debugging":
$(document).ready(function() {
show_properties();
// You might also put an alert at the very end of show_properties.
alert('show_properties called; now calling table_events()');
table_events();
alert('table_events called; document.ready done');
});
There is probably an error in the table_events function. Try debugging using simple alert statements.

How to resolve this ReferenceError?

I have a web application based on Django. I use the Scrapy Crawler to crawl webpages. My goal, at the moment, is to be able to control the crawler from within a webpage using jQuery and AJAX requests.
My theoretical setup is the following:
On the webpage, I have a button. When I click the button, the crawler is started on the server-side.
Once the crawler has started, I periodically send AJAX GET requests to the server using window.setInterval to find out how many webpages have been crawled so far.
Once the crawler has finished, the GET requests should stop by using window.clearInterval.
These are the relevant lines from my current code:
$(document).ready(function() {
// This variable will hold the ID returned by setInterval
var monitorCrawlerId;
$startCrawlerButton.on('click', function(event) {
// This function should be run periodically using setInterval
var monitorCrawler = function() {
$.ajax({
type: 'GET',
url: '/monitor_crawler/',
// ...
success: function(response) {
// if the server sends the message that the crawler
// has stopped, use clearInterval to stop executing this function
if (response.crawler_status == 'finished') {
clearInterval(monitorCrawlerId);
}
}
});
};
// Here I send an AJAX POST request to the server to start the crawler
$.ajax({
type: 'POST',
url: '/start_crawler/',
// ...
success: function(response) {
// If the form that the button belongs to validates correctly,
// call setInterval with the function monitorCrawler defined above
if (response.validation_status == 'success') {
monitorCrawlerId = setInterval('monitorCrawler()', 10000);
}
}
});
});
});
The problem: When I execute this code, I get this in Firefox's web console:
ReferenceError: monitorCrawler is not defined
The strange thing, however, is that the function monitorCrawler gets periodically executed anyway. But with every execution, I get the same error message again. If I put monitorCrawler outside of $startCrawlerButton.on() I still get the same errors. How can I resolve this? Since I'm a JavaScript newbie, any help is appreciated. Thank you very much!
setInterval, when first parameter is string, resolves in the global (window) context. You can give it a variable pointing to the function to be called or even:
setInterval(function(){monitorCrawler();}, 10000);
this will create a closure where local variable monitorCrawler will still exist when interval fires.
Change
setInterval('monitorCrawler()', 10000);
to
setInterval(monitorCrawler, 10000);
Never ever pass strings to setInterval, but function references! They will be evaled every time, and that in global scope - yet your monitorCrawler function is local to the click-handler (and I guess by "putting it outside" you meant "into the ready-callback").
Try
monitorCrawlerId = setInterval(monitorCrawler, 10000);
With parameters:
monitorCrawlerId = setInterval(function(){
//prepare params.
monitorCrawler(/* param1, param2*/);
}, 10000);

Twitter API and Node

I'm trying to retrieve my last tweet from Twitter with https://github.com/jdub/node-twitter
I want to declare a variable, change that variable within a function, then use it again outside that function. Is this possible?
I have authenticated and can see my last tweet if I do:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet);
});
But I want to separate my code out and do:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
});
console.log(tweet);
Tweet is still undefined.
Please educate me :-)
You want to be able to console.log immediately but node.js is not synchronous and that's what makes it so powerful and fast. You have to get used to an asynchronous pattern of coding with node.js. The get request is async. Tweet doesn't get assigned until the callback happens.
Console.log executes immediately after the async request is made.
Try: (EDIT- I suggested this and then question was edited to include this code)
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet); // executed after call returns
});
// executes immediately after request is sent
console.log("request sent");
Notice that the second argument to the twit.get call is an anonymous function that will get executed after it has completed the async request.
The output of this should be "request sent" and then the tweet result in that order.

I'm new to javascript and I'm fetching JSON data from url, I'm only able to access data in success function, Am I missing something?

Here is the code :-
var quiz;
function startQuiz() {
$.ajax({
url: 'get_quiz/',
cache: 'false',
dataType: 'json',
async: 'false',
success: function(data) {
quiz = data;
alert(quiz[0].q); // I'm able to access quiz here
},
}
);
}
startQuiz();
alert(quiz[0].q); // Not able to access it here.
I'm not able to access quiz here, am I mission something?, Whats wrong with this?
Ajax is assynchronous which can be an unfamiliar concept. Your code will run like this:
1. var quiz;
2. define function startQuiz;
3. call startQuiz;
4. do ajax call (and continue! don't block)
5. alert(quiz[0].q); // Not able to access it here.
-- ajax call comes back
6. quiz = data;
7. alert(quiz[0].q); // I'm able to access quiz here
Ajax is asynchronous, it doesn't block. This means that when you make the ajax call the callback doesn't actually get called until the ajax call returns, it doesn't block and wait. Instead the code will continue on.
Then later when the ajax call returns the data, your callback function will be executed.
Javascript does this by means of an event loop.
See it like this: steps 1-5 are part of the first event. 6-7 are part of the second event.
A cool thing about JavaScript is that in your callback you still have access to anything above it (like the variable quiz) because of scoping. This is called a closure. Your callback function closes around the scope and brings it with him to the next event.
AJAX calls are asynchronous, you should wait for the result to come back from the server. Either do all the work in a callback function or have a look on a promises library (I like Q promises library), which makes waiting for AJAX results very easy.
This is due to the asynchronous nature of JavaScript, once you call startQuiz() it executes and jumps back out and executes your quiz alert().
You have to access your quiz data explicitly after the callback is called to make sure you have access to it.
You also have to worry about scoping, as you may not be actually modifying the same quiz variable.
var quiz,
fetched = false;
$.ajax({
//blah
success : function(data){
fetched = true;
quiz = data;
}
});
setInterval(function(){
if(fetched){
//quiz is populated
}else{
//quiz hasn't be populated yet
}
},50);
Although not a clever example, I'm just trying to get the point across that startQuiz() doesn't wait for the ajax call. The A in AJAX mean asynchronous.
You should give jQuery deferreds a try which ist the preferred way of writing ajax related code since jQuery 1.5: http://javascriptplayground.com/blog/2012/04/jquery-deferreds-tutorial
Once you get the hang of it maybe will be easier to write and understand your code.

How to obtain jquery post return values?

I want to retrieve the height and width of an image on a server by using an ajax post call to a php file which returns a double pipe delimited string 'width||height'
My javascript is correctly alerting that requested string from the php file so the info is now in my script but i cannot seem to access it outside the $.post function.
This works:
var getImagesize = function(sFilename)
{
$.post("getImagesize.php", { filename: sFilename, time: "2pm" },
function(data){
alert(data.split('||'));
});
}
But retrieving is a different matter:
// this line calls the function in a loop through images:
var aOrgdimensions = getImagesize($(this, x).attr('src')) ;
alert(aOrgdimension);
// the called function now looks like this:
var getImagesize = function(sFilename)
{
var aImagedims = new Array();
$.post("getImagesize.php", { filename: sFilename },
function(data){
aImagedims = data.split('||');
});
return "here it is" + aImagedims ;
}
Anyone able to tell me what i'm doing wrong?
You are misunderstanding the way that an AJAX call works. The first "A" in AJAX stands for asynchronous, which means that a request is made independent of the code thread you are running. That is the reason that callbacks are so big when it comes to AJAX, as you don't know when something is done until it is done. Your code, in the meantime, happily continues on.
In your code, you are trying to assign a variable, aOrgdimensions a value that you will not know until the request is done. There are two solutions to this:
Modify your logic to reconcile the concept of callbacks and perform your actions once the request is done with.
Less preferably, make your request synchronous. This means the code and page will "hang" at the point of the request and only proceed once it is over. This is done by adding async: false to the jQuery options.
Thanx for the Asynchronous explaination. I did not realize that, but at least now i know why my vars aren't available.
Edit: Figured it out. Used the callback function as suggested, and all is well. :D

Categories

Resources