Ajax triggering body's onLoad event - javascript

My whole page is loading again whenever I make a ajax call to load a div.
I have noticed that 'body onload=init()' onload event is getting triggered on ajax response and all the initialization is happening again. I don't want that to happen.
Is there a way by which only div is loaded through ajax call.
<body onload="init()">
.....
.....
<div>...<b>More</b></div>
</body>
main.js
function saveView(arg){
if(arg=="more"){
ajaxGet(baseRef+"all.html", loadList);
}else{
ajaxGet(baseRef+"all-A.html", loadList);
}
function init(){
.....
}
function ajaxGet(url, responseHandler)
{
var page_request = false;
if (window.XMLHttpRequest && !(window.ActiveXObject && window.location.protocol == "file:")) {
// use this only if available, and not using IE on a local filesystem
page_request = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // older versions of IE, or IE on a local filesystem
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
}
}
}
else {
alert("Your browser does not support XMLHTTP.");
return false;
}
page_request.onreadystatechange=function() {
if(page_request.readyState==4) {
// on local machines the status for success is 0. on web servers it is 200
if(page_request.status==200 || page_request.status==0) {
responseHandler(page_request);
}
}
}
page_request.open('GET', url, true);
page_request.send(null);
}
function loadList(page_request){
document.getElementById("list").innerHTML=page_request.responseText;
Loaded = true;
try{
if(pLoaded)
doFilterStateChange1();
}catch(e)
{
}
setTimeout("restoreScrollTop()", 1000);
}

It is not ajax that is triggering onLoad event of body.
If you see the anchor tag, I haven't assigned any value to href="" which was causing the page to be loaded again. Removing it solved the problem.

We'd need to see your code to help, but when pages do things like reloading etc, it usually means their is a script error. Use firebug to check for errors, it might be hard to catch if it's refreshing quickly.

Related

Load another html page without changing URL

I have some problem with page load on desktop browser and mobile browser. In this case I have 4 html page one is home.html, second is home-mobile.html, third is product.html and fourth is product-mobile.html. My problem is I don't know to switch the html page if opened in mobile browser. For the example is when I open www.example.com in desktop the page will call home.html but when I open www.example.com in mobile the page will call home-mobile.html and so with product page, when I open www.example.com/product in desktop it will call product.html but when I open www.example.com/product in mobile it will call product-mobile.html. The point is how could I open one link and it will detect opened in desktop browser or mobile browser and call different html page.
Which I have been done now but still not working is :
<script>
window.mobilecheck = function() {
var check = false;
if(window.innerWidth<768){
check=true;
}
return check;
}
if(window.mobilecheck()){
window.location.href="home-mobile.html";
}
else {
window.location.href="home.html";
}
</script>
But with that script the URL was changing and not be the same.
Please anyone know how to do this could help me. Thanks.
This script allows you to change the page content without redirecting the browser.
window.mobilecheck = function() {
var check = false;
if (window.innerWidth < 768) {
check = true;
}
return check;
}
if (window.mobilecheck()) {
$.ajax({
'type': 'POST',
'url': 'home_mobile.html',
'data': postData,
'success': function(response) {
$("html").html(response);
}
});
}
modify the code as you need.
If your device mobile it will automatically redirect on mobile page. Simple use this code. No need for else condition. just check mobile device.
if ($(window).width() < 767) {
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
"Android"
if (/windows phone/i.test(userAgent)) {
return "Windows Phone";
}
if (/android/i.test(userAgent)) {
return "Android";
}
if (/iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "unknown";
}
if(getMobileOperatingSystem()){
window.location="\home-mobile.html";
}
}
Let's say your page is home.html.
And when the page is loaded, you can run a script to detect client type( desktop or mobile), then send an Ajax call to corresponding page to get the content you want.
Then when the Ajax call returned, you can simply replace current content with the returned value.
In this way, your URL will not change at all, and the content can change according to current client type.
home.html:
<html>
<head>
<script language="javascript">
function loadContent(){
var clientType
//your code to get client type here
//Below block to get Ajax client object according to your browser type
var XHTTP;
try
{
//For morden versions Internet Explorer
XHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex)
{
try
{
try
{
//For old versions Internet Explorer
XHTTP=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(exxx)
{
XHTTP = new XMLHttpRequest("Msxml2.XMLHTTP");
}
}
catch(exx)
{
try
{
//For browsers other than Internet Explorer
XHTTP= new XMLHttpRequest();
}
catch(eexx)
{
//This means ActiveX is not enabled.
//To enabled go to your browser settings and enabled the ActiveX.
alert("Not Supported, It might be previous version browser");
}
}
}
if(clientType=="mobile"){
XHTTP.open("GET","/home_mobile.html");
}else{
XHTTP.open("GET","/home_desktop.html")
}
XHTTP.onreadystatechange= function()
{
if (XHTTP.readyState==4)
{
var result=XHTTP.responseText.toString();
document.getElementById("content").innerHTML=result;
}
}
//This finlly send the request.
XHTTP.send(null);
}
</script>
</head>
<body onload="javascript:{loadContent();}">
<div id="content"></div>
</body>
</html>
This script will change the html content of a current page with requested page html without changing url. (AJAX)
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object
xhr.onload = function() { // When response has loaded
// The following conditional check will not work locally - only on a server
// if(xhr.status === 200) { // If server status was ok
document.getElementsByTagName("html")[0].innerHTML= xhr.responseText; // Update
//}
};
xhr.open('GET', 'html u want to replace ', true); // Prepare the request
xhr.send(null); // Send the request
});

Ajax iframe request only works once in Internet Explorer

I'm using an ajax script to show a loading animation in an iframe while a php script runs. Once the php script finishes running the ajax loading script loads the finished php scripts output.
Update: I have resolved this by replacing:
url='action.php?run=go';
http.open("GET",url, true);
with:
http.open( "GET", "go.php?random=" + Math.random(), true);
I read that IE caches each request and doesn't like sending the requests more than once.
<!DOCTYPE html>
<script type="text/javascript">
document.write('<link rel="stylesheet" href="../css/loading.css" type="text/css" /><div id="loading"><br><center>Please Wait...<br><br><img src="loader.gif"/><center></div>');
//Ajax Function
function getHTTPObject() {
var xmlhttp;
if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
} else {
xmlhttp = false;
}
if (window.XMLHttpRequest) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction() {
url = 'action.php?run=go';
http.open("GET", url, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
//Change the text when result comes.....
document.getElementById("loading").innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
Try the xmlhttp = new XMLHttpRequest(); stuff before you test for the ActiveXObject. The latter is used for compatibility with older versions of IE (IE 5 & 6 I believe). However, newer versions of IE support the use of the XMLHttpRequest object. You might also try indenting properly to make your code readable.
Additionally, since you mentioned you're new to JS & AJAX, you really should look into using jQuery which makes using AJAX incredibly easy. I personally use jQuery as well as my own AJAX function, so, in practice, what you're doing is perfectly fine. But if you would rather do without the hassle then jQuery is the way to go.
Can you use jQuery? It has all the boiler plating for ajax you need in $.ajax

Is there AJAX progress event in IE and how to use it?

I tried all I could think of to at least get to the progress function in IE9 but nothing works. All other browsers get inside of the progress function and write test text without any problems. Hopefully someone can help me. Thank you!
var info = document.getElementById('info');
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
xhr.attachEvent("onprogress", function(e) {
info.innerHTML += "loading...<br />";
});
/*xhr.addEventListener("progress", function(e) {
info.innerHTML += "loading...<br />";
}, false);*/
xhr.open("GET", "10_MB_File.txt", true);
xhr.send(null);
The onprogress event is part of the XMLHttpRequest Level 2 spec...
http://www.w3.org/TR/XMLHttpRequest2/
http://www.w3.org/TR/XMLHttpRequest2/#event-handlers
... which is not supported by IE 9 and below. However, IE 10 is supposed to support it...
http://msdn.microsoft.com/en-us/library/ie/hh673569(v=vs.85).aspx#Enhanced_Event_Support
For more information on which browsers support XHR Level 2, take a look at caniuse.com...
http://caniuse.com/#feat=xhr2
IE9 and under do not support onprogress, hence why you can not get it to work.
var xhr = new XMLHttpRequest();
console.log('onprogress' in xhr);
You could use the onreadystatechange event and display your message. I'm just suggesting it as a workaround.
xhr.onreadystatechange=function() {
if (xhr.readyState != 4) {
// Display a progress message here.
} else if (xhr.readyState==4 && xhr.status==200) {
// Request is finished, do whatever here.
}
}
Adding to suggestion list, if JQuery is used in your project. It can be achieved by below functions and ofcourse, it needs to be JQuery $.ajax request. Advantage of these client libraries is they have objects instantiated based on browsers. For ex: JQuery takes care of "ActiveXObject("Msxml2.XMLHTTP")" or "ActiveXObject("Microsoft.XMLHTTP")" based on browser.
//displays progress bar
$('#info').ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});

Javascript Not Executing In Dynamically Loading Content (AHAH)

I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.

Replacing whole HTML content kills HEAD and BODY tags after HTTP Request!

After pressing a button, I'm sending the whole HTML content from a webpage (the part within the <html> tags) to a CGI script which manipulates the content and sends it back.
Now I'm trying to replace the existing content with the new one. Unfortunately after assignment, every single <head> or <body> tag (as well as the closing ones) will be killed.
By using some alerts I looked through the returning value as well as the original HTML stuff. Both are absolutely as expected.
But after the assignment there is some magic going on. Please help me to figure out what's going on.
Here is the used JavaScript code I used:
var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);
makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);
function makePOSTRequest(method, url, parameters, htmlNode) {
var http_request = getRequestObj();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function()
{
if (http_request.readyState < 4)
{
var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
document.body.innerHTML = waitingPageBody;
}
else //if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
alert('1response: ' + http_request.responseText);
alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
}//end of if (http_request.status == 200)
else
{//other http statuses
alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
bodyNode.innerHTML = originalBodyInnerHTML;
}
}//end of else if http_request.readyState == 4
}
http_request.open(method, url, true); //async
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function getRequestObj() {
var http_request = false;
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
This is a simple solution that worked for me. Just as a reference.
document.clear();
document.write(newHtml);
where newHtml is the complete html of new web page.
well, with this
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText
you are replacing everything insidee the html, "killing" body, head and everything...
maybe you wanted
document.body.innerHTML = http_request.responseText
Also, I'd use jquery, it makes your life sooo much easier
You cannot do that. It's not possible to replace the contents of the whole html tag. You can get away with replacing only the contents of the body tag. The head element is kind of magical and browser generally don't support replacing it.
If you want to change the whole document, redirect to it.
If you want to change only parts of the head, try sending them in a different form (like JSON), and make appropriate changes using javascript APIs.
Thanks qbeuek for your answer!
To change only the header, Firefox in fact will allow something like this:document.getElementsByTagName('head')[0] += "e.g. some scripts"
But for Internet Explorer it is necessary to add each element separately to the DOM tree.
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script);
However, it is really weird that Firefox behaves like this and not popup with some error...

Categories