2 AJAX wont work - javascript

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

Related

Timing on GET info from PHP/SQL

Just for you to know I'm less than a newbie!
I have the following javascript code:
window.onload = function() {
renderTime();
getsec(myHandler);
countdown('countdown');
...
}
function myHandler(resultado) {
seconds = resultado;
}
function reqListener () {
console.log(this.responseText);
}
function getsec(callback) {
var indice = 1;
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var variarr = JSON.parse(this.responseText);
callback(variarr[0]);
};
oReq.open("GET", "getsec.php?lei="+indice, true);
oReq.send();
}
This works perfectly for me. The intention is to get data from MySQL table through getsec.php every second. As you can see I have function countdown('countdown') that looks like this:
function countdown(element) {
...
interval = setInterval(function() {
...
if( runned == false){ // This condition happens
...
} else {
...
}
}, 1000);
}
I tryed to put function getsec(myHandler) inside function countdown('countdown')
if( runned == false){ // This condition happens
getsec(myHandler);
and I stop getting the information I want.
Can anyone explain me why?

why javascript refuses to work more than once?

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.

Stop html submit button in js ajax function

I want to stop the submit button in the js function checkUni()
Usually in js you can just return false, but that it not gonna work in my case because its an asynchronous (ajax)function, so the outer function will return before the inner function is able to determine wether to return false or true.
Here is the js function:
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var container = document.getElementById("container_ID"); //destination of returned data
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
request.open("GET", URL, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
//SOME CODE
//IF <something> then STOP SUBMIT BUTTON
container.innerHTML = request.responseText;
}
}
request.send(null);
}
Simply return false in the onclick listener.
<input type="submit" onclick="checkUni(); return false;"/>
You can set the action of the form element to "#" which will have the same effect.

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