why javascript refuses to work more than once? - javascript

I have two separate links that call same function. They are used to load different external html doc into body of main one. They work correctly by themselves. But when one doc is loaded another one refuses to. What is a problem guys?
<li>
<a href="#" class="decorNavi" onclick ="xmlRequest('about')" >ABOUT</a>
</li>
<li>
<a href="#" class="decorNavi" onclick ="xmlRequest('contactus')" >CONTACT US</a
</li>
Script:
function xmlRequest(target) {
var targetClick;
targetClick = target;
if (window.XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
} else {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("GET", targetClick + ".html?=" + Math.random(), true);
xmlRequest.onreadystatechange = function () {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
document.getElementById("midContainer").innerHTML = xmlRequest.responseText;
}
}
xmlRequest.send();
}

You're overwriting your function declaration inside your function:
function xmlRequest(target) {
and
xmlRequest = new XMLHttpRequest();
It fires once, and then replaces the function with the xmlRequest. Name the second one something else.

As Mike Robinson said, you are overwriting your function. Use an other name for your function. As easy as that.
function xmlRequest(targetClick) {
var xmlRequest; // xmlRequest is no more a global.
if (window.XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
} else {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("GET", targetClick + ".html?=" + Math.random(), true);
xmlRequest.onreadystatechange = function () {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
document.getElementById("midContainer").innerHTML = xmlRequest.responseText;
}
}
xmlRequest.send();
}
JSbin: http://jsbin.com/kehaxexo/2/

The name of you function "xmlRequest" and object defined in it are the same. change it to something else.

Related

Using AJAX to change div content - how do I display navigation as hash / anchor

I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div. (e.g. www.website.co.uk/#page1)
I've managed to make it so that the content can be updated for 1 page, however, if I add multiple pages it stops working
Additionally - if I was to navigate to the URL website.co.uk/#page1 it wont display #page1.
Can anyone help?
This is my current code:
HTML :
<h5> Test</h5>
<h5> Test2</h5>
JS :
<script type="text/javascript">
var routes = {
'#page1' : '{{site.url}}/page1'
'#page2' : '{{site.url}}/page2'
};
var routeHandler = function( event ) {
var hash = window.location.hash,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
</script>
You made some small js errors.
So here is you fixed code
html:
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
javascript:
//change these routs
var routes = {
'#page1': '/page1.html',
'#page2': '/page2.html'
};
var routeHandler = function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[window.location.hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(window.location.hash)) routeHandler();
});
You usually use a router-like object for this. Instead of the hyperlink you're using, set the href to the actual page hash Button Title. Then create an event listener for the hashchange on the window object where you will fetch the content.
And finally add a list of webpages you want to be able to navigate to, so you can translate '#page1' to the actual url.
The result is that you can use simple hrefs in your hyperlinks and the current page will be shown in the url bar at the top.
ps: add a check into the hashchange listener for routes that aren't listed, so you can still link to offsite pages as well.
pps: If you want to be able to directly navigate to a page, you'll need to add a manual check of the hash at document load.
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
window.addEventListener('hashchange', function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
});
Updated with a load listener:
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
var routeHandler = function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
since you have tagged the question with jquery, iassume you have jQuery available, in this case you could do something like:
$(window).on('hashchange', refreshContent);
function refreshContent() {
$.get(getBaseUrl() + location.hash, function(data) {
$('#div1').html(data);
});
}
But please be aware that there are a lot more sophisticated solutions out there
I given directly on onclick its working. It may help you.
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
<script type="text/javascript">
var routes = {
'#page1' : 'page1.html',
'#page2' : 'page2.html'
};
function test(page) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[page], true);
xhttp.send();
}
</script>
I used .html for pages for check. You use your own.

on delete link popup are you sure

I have link <a href="/MyData/Delete/"> Delete data
How can I implement onclick to popup confirm action with text are you sure and if yes selected to proceed to HttpPost action on MyData/Delete?
<a href="/MyData/Delete/" onclick="someFunction(this, event)">
In javascript:
function someFunction(target, event) {
if(confirm("Are you sure to delete?")) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// successfully deleted
}
};
xhr.open("POST", target.url, true);
xhr.send();
} else {
event.preventDefault();
}
}
More cleaner way of doing:
<a href="/MyData/Delete/" class="confirmlink">
document.querySelector(".confirmlink").addEventListener("click", function(event) {
if(confirm("Are you sure to delete?")) {
window.location.href = this.href;
} else {
event.preventDefault();
}
});
Avoid using inline js scripts in HTML. It will pollute the markup and tough to manage later.

2 AJAX wont work

When I run my page only 1 ajax get to work... Im pretty sure it has something to do with the setInterval "property"...
<script>
function encontrarnumero() {
src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid = 'u219-4';
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
setInterval(encontrarnumero, 1000);
}
};
xmlhttp.open("GET", "numero.php?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
window.onload = function () {
encontrarnumero();
};
</script>
<script>
function encontrartiempo() {
src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid = 'tiempo';
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
setInterval(encontrartiempo, 2000);
}
};
xmlhttp.open("GET", "tiempo.php?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
window.onload = function () {
encontrartiempo();
};
</script>
any ideas?? Thanks!!
ps. im sure the problem are not the php files, when I run each ajax by itself they work fine.
Too much repeating code. Things are much simpler if you refactor your code into a single function.
<script>
// Move repeating code to a function
function doAJAX(divid, page) {
if (window.XMLHttpRequest) {
// Use `var` when declaring variables
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
// Use `setTimeout` if you're going to make recursive calls!
setTimeout(function() {
doAJAX(divid, page)
}, 1000);
}
};
xmlhttp.open("GET", page + "?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
// Just one onload handler that calls the function twice,
// passing the different info for each call
window.onload = function () {
doAJAX('u219-4', "numero.php");
doAJAX('tiempo', "tiempo.php");
};
</script>
The problem with your original code was that your were assigining to window.onload twice and the second assignment overwrote the first. Thats why encontrarnumero() was never called.
Note that Crazy Train's answer only makes a single assignment to window.onload.
Lastly, assigning to window.onload like this is not really the best approach. if you want to do something when the window loads, consider using JQuery or using native browser events if you want pure javascript. you can see how JQuery actually does this in this answer

AJAX function parameter is null?

i got a problem with JS:
On line 1 to 4 I take all "a"-Elements from the DOM and get their hrefs.
later I want to reload the URL via AJAX, but the href does not arrive correctly... Whats wrong?
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
function ajaxReload(href) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", href, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState != 4) {
document.write('loading');
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('hello');
//alert('getting '+xmlhttp.status+' for '+href);
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
var writeContent = document.getElementById('content');
writeContent.innerHTML = ajaxContent;
}
}
xmlhttp.send(null);
}
Sorry if I've misunderstood your code. I think that you simply need to (at least approximately) just remove code as commented below:
//$('a').click = function(href) {
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
$("content").html(ajaxContent);
// ajaxReload(href); //this would cause a loop?
// return false;
//}
To answer your later question - you can change your event propagation handling to:
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
And for the further comments, maybe try changing your:
document.write('loading');
To:
$("content").html(xmlhttp.status); //so now you can see the loading status for testing

How can the right part of page of Google videos stay still when you search videos on the left

When you use Google Videos, you will notice the right part of the page stays still when you search videos on the left. How is it implemented?
using ajax
http://www.google.com/search?q=ajax+tutorial
edit:
function $(id) { return document.getElementById(id); }
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AJAX_GetAsinc(ajax, id, url) {
ajax.abort();
function statechange() {
if ((ajax.readyState==4) && (ajax.status==200)) $(id).innerHTML=ajax.responseText;
}
ajax.open('GET', url, true);
ajax.onreadystatechange = statechange;
ajax.send(null);
}
usage:
var a = getHTTPObject();
AJAX_GetAsinc(a, 'YOUR_DIV_ID', 'mycontent.php');
or:
use jQuery or your favourite framework/library
Hope it's specific enough

Categories