Stop page refresh

haakym picture haakym · Apr 26, 2012 · Viewed 9.1k times · Source

I'm writing a small piece of code which takes input from a user via html form to then retrieve information (in xml) from a server (which is running locally) using XMLHttpRequest, once I get the information I output it into a list using the method I've written for the onreadystatechange. However once it's written the list to the page it automatically refreshes the page and the list disappears. I'm absolutely lost as to why it is doing this?! I've managed to forcefully stop the page refreshing using window.onbeforeunload and stopping the refresh, but I can't help but think there is a better way around this and that I must be doing something wrong. My code is as follows:

var xmlhttp=null;

function byObserver(){

var a = document.forms["byObserverForm"]["observerName"].value;
a = encodeURIComponent(a);

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
    xmlhttp.onreadystatechange = onReadyStateByObserver;
    xmlhttp.open("GET","http://localhost:8004/birdobs/observer/" + a, false);
    xmlhttp.send();   
} 
return false;

}

function onReadyStateByObserver(){

if (xmlhttp.readyState == 4){

    if (xmlhttp.status == 200){

        var xmlDoc = xmlhttp.responseXML;
        var observations = xmlDoc.getElementsByTagName("observation");

        if (observations.length != 0){

            // output into unordered list 
            var f = document.createDocumentFragment();
            var e = document.createElement("ul");
            f.appendChild(e);
            var ul = f.firstChild;

            for (i = 0; i<observations.length; i++) {
                var li = document.createElement("li");

                var te = document.createTextNode(observations[i].getAttribute("observer"));
                li.appendChild(te);
                ul.appendChild(li);
            }  // end for 
            document.getElementById("content").appendChild(f);

            window.onbeforeunload = function(){
                return "Refresh";
            }


        }
    }
} 
//have also tried return false here

}

Any help would be highly appreciated as I've spent so long trying to fix this, many thanks in advance! (I haven't included the HTML as I thought it wasn't needed, but please ask if it would help and I'll post it up!) I'll just finally add I'm running this in chrome.

Answer

Fabrizio Calderan picture Fabrizio Calderan · Apr 26, 2012

you should stop the default event when you submit the form, e.g. with return false at the end of the function called on submit. Maybe the page is refreshing because you're not stopping the submit event (and the browser is thus redirected to the page specified on action attribute of your form)