views:

30

answers:

4

I'm using the following code to call a function when the main browser's url changes.

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIWebNavigation)
                     .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                     .rootTreeItem
                     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIDOMWindow); 

      mainWindow.getBrowser().addEventListener("DOMContentLoaded",function(){ getFromDB();}, false);

This getFromDB() sends a request to the server

request = new XMLHttpRequest();
request.open("GET", "http://www.mydomain.com/getJSON.php", true);
request.onreadystatechange = sendData;

Everything is working fine, but the problem is that the request is being sent to the server for infinite number of times. If the browser is loaded with a page within loacalhost then the request is sent only once.

I want to restrict the request to be sent only once per page load/request (or URL change).

I've used some Boolean check. But they ain't work.

var check=0;
if(check==0)
{
check=1;
getFromDb();
}

inside the first addEventListener in line:8 Help me to get this.

A: 

you need a global variable for that

if(window.check==0||typeof(window.check)=="undefined")
{
window.check=1;
getFromDb();
}
Christian Smorra
I've used global variables even. But I'm not getting the result.
Vinothkumar Arputharaj
A: 

Is this line correct? If i assume the function name as sendData then it may be sending data again on ready state change:

request.onreadystatechange = sendData;

What is sendData doing?

naikus
`sendData` is a function. This line is calling `onreadystatechange`.
Vinothkumar Arputharaj
Maybe sendData is again doing the ajax call. The onreadystatechange will be called several times (4)
naikus
A: 
var listener = function(e){
    getFromDB();
    mainWindow.getBrowser().removeEventListener("DOMContentLoaded",listener, false);
}

mainWindow.getBrowser().addEventListener("DOMContentLoaded", listener, false)

Something like that anyways.

Do not introduce globals or flags, just use the listener system properly.

BGerrissen
This seems working partially. At once the page is refreshed/reloaded, the eventlistener gets removed from the DOM.I want to load the event listener on url change and the corresponding function should be called only once.
Vinothkumar Arputharaj
A: 

I also think that you need a global var. Use global var and inside getFromDb(), change value of the var to something so that you can check whether this var is set or not.

var check = 0;
if (check == 0) {
getFromDb();
}

function getFromDb() {

....
...
check = 1;
...
}
Satya Prakash