Calling a function cancels out the previous action - javascript

I have a simple script that i am testing with, but its acting very odd. I call a script which loads and i have it to a particular td id, I then call a second script and add that to different td id but for some reason it wipes out the first div's content even though they are seperate.
This is what i have:
function call_back(result,div_id,func){
document.getElementById(div_id).innerHTML = result;
if(typeof(func) != 'undefined'){func();}
}
function caller(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function call_file(url,div_id,func){
caller(url,function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
call_back(xmlhttp.responseText,div_id,func);
}
});
}
I then have this on my onload:
window.onload = function(){
stage = 6;
call_file('test.html','menu_left');
switch(parseInt(stage)){
case 6: call_file('test2.html','main'); break;
}
};
The problem arises with the case statement. If i remove the case statement the contents added with test.html loads fine, but if i add the case statement, content from test.html disappears and then only test2.html displays.
The html for the id's are:
<table class="body_wrapper">
<tr>
<td class="menu_left" id="menu_left"></td>
<td class="main" id="main"></td>
</tr>
</table>
Why might this be happening?

The problem has nothing to do with the switch statement. As you are calling the ajax request for some local files and it is already cached, the call_back function is called twice before document.getElementById(div_id).innerHTML = result; executes and hence replaced by the variable values from the last call. If you just put an alert into the call_back function like below
function call_back(result, div_id, func) {
alert(result);
document.getElementById(div_id).innerHTML = result;
if (typeof (func) != 'undefined') { func(); }
}
you will find it is working. But as it is not a solution, alternatively if you modify this
xmlhttp.open("GET", url, true);
to
xmlhttp.open("GET", url, false);
it will work but you will loose the asynchronous feature of AJAX.

Related

Javascript, ajax timing issues

I am having a problem with calling 2 separate ajax functions. I have a loop that loops through all checkbox elements on the page then if they are checked it calls an ajax function that moves some data in my database. Then outside of the for loop i call another ajax function that goes to my database and pulls the results back to my ID element. I have had to name my httprequests differently so they dont fight, Both functions work but the one outside my loop goes to fast and doesnt pull the new/changed data. If i put an alert before this outside loop function it then works. I have also tried to use a setTimeout(myFunctio(), 3000) with no luck.
Here is my code.
function ungroupContact(){
group = document.getElementsByName("moveGroup")[0].value;
for(i=0;i<=25;i++){
if(document.getElementById('checkBox'+i)){
if(document.getElementById('checkBox'+i).checked){
var email = document.getElementById('checkBox'+i).value;
moveContact(email, group);
}
}
}
//alert("hello");
//setTimeout(alert("hello"),12000);
groupList1(group);
}
This is my first time posting, sorry if this is noobish, currently studying my degree in computer science.
Thanks for any suggestion and/or help
Sorry i should have known to put up the ajax functions. I have used the layout from w3schools.
function moveContact(email, group){
if (email=="" || group=="")
{
document.getElementById("sidebar2").innerHTML="Something wrong was entered";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
if (xmlhttp1.readyState==1 || xmlhttp1.readyState==2 || xmlhttp1.readyState==3)
{
document.getElementById("sidebar2").innerHTML="<img src='images/loading.gif' alt='Loading'> ";
}
if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
{
document.getElementById("sidebar2").innerHTML=xmlhttp1.responseText;
}
}
xmlhttp1.open("GET","core/moveContact.php?group="+group+"&email="+email,true);
xmlhttp1.send();
return;
}
You will need to keep track of when the last moveContact() asynchronous ajax function is done and then (and only then), call groupList1().
Since you have not disclosed the moveContact() code where the ajax calls are probably being done, we can't really recommend specifics on tracking them. One simple technique is to set up a counter of pending ajax calls and in each success handler for the moveContact() ajax calls, check to see if the counter has now reached zero. If so, you can then call groupList1(group).
Assuming you added a completion callback to moveContact(), you could do it like this:
function ungroupContact(){
group = document.getElementsByName("moveGroup")[0].value;
var contactsRemaining = 0;
for(i=0;i<=25;i++){
if(document.getElementById('checkBox'+i)){
if(document.getElementById('checkBox'+i).checked){
++contactsRemaining;
var email = document.getElementById('checkBox'+i).value;
moveContact(email, group, function() {
--contactsRemaining;
if (contactsRemaining === 0) {
groupList1(group);
}
});
}
}
}
}
function moveContact(email, group, fn){
if (email=="" || group=="") {
document.getElementById("sidebar2").innerHTML="Something wrong was entered";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==1 || xmlhttp1.readyState==2 || xmlhttp1.readyState==3) {
document.getElementById("sidebar2").innerHTML="<img src='images/loading.gif' alt='Loading'> ";
}
if (xmlhttp1.readyState==4 && xmlhttp1.status==200) {
document.getElementById("sidebar2").innerHTML=xmlhttp1.responseText;
// we are done now, so call the finish callback
if (fn) {
fn();
}
}
}
xmlhttp1.open("GET","core/moveContact.php?group="+group+"&email="+email,true);
xmlhttp1.send();
return;
}
You can add callback function on success and in that function execute groupList1 function when all methods finish executing:
var finished = 0;
moveContact(email, group, function() {
if (++finished == 25) {
groupList1(group);
}
});

How Can 2 onload() JavaScript Scripts be Loaded?

With this function:
function start() {
MONDUX();
Biggie();
}
function MONDUX executes, and the AJAX call returns good data and is displayed correctly.
However, Biggie() is a.w.a.l.
The result of this :
function start() {
Biggie();
MONDUX();
}
is the opposite. Biggie() works as expected, MONUX() fails.
This doesn't do any good, down in the body:
<script type="text/JavaScript">
window.onload= start();
</script>
and, this dodge is not helpful:
<body onload="start()">
and that was tried like so also
Detest cargo~cult programming and running out of ideas here. Suggestions?
These resources were all related // near hits // no cigar.
Loading javascript in body onload with 2 functions
JS and Body(Window) Onload event
JavaScript: How is "function onload() {}" different from "onload = function() {}"? That one
was fascinating but way deep waters for me...
How to onload two javascript files? meh... good, but...
?? :/~
<script type="text/javascript" >
function MONDUX(){
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("WhatThexBobby").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS 22solo PHP.php?figure1=5&figure2=33", true);
xmlhttp.send();
alert(WhatThexBobby);
}
</script>
<script type="text/javascript" >
function Biggie(){
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("FreakinEh").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS solo PHP.php?figure1=5&figure2=10", true);
xmlhttp.send();
alert(FreakinEh);
}
</script>
You're assigning the request to the global variable xmlhttp, and then reassigning that variable to another request before the first one has returned. I don't know if that is causing your problem, but it's definitely going to cause a problem. It's also very bad JavaScript practice.
Simple fix is to put the line 'var xmlhttp;' at the beginning of both functions.
Edit: Just in case you didn't know this: xmlhttprequest is asynchronous. You call 'send', and your remaining statements in the script and document continue to run while the request is being sent to the server. Only after the server returns do the various callback methods (onreadystatechange, and the like) get called, and this is long after your alerts were shown.
Considering one of them is throwing some error, would it not be good idea to put them in Try Catch ? Something like,
function start() {
try
{
MONDUX();
}
catch(err)
{
// handle error
}
try
{
Biggie();
}
catch(err)
{
//Handle error
}
finally
{
// cleanup
}
}
This will ensure both runs even if one of them mis-fires.

ajax internet explorer onchange

My ajax script for loading the second select box, works in firefox and chrome, but internt explorers cant handle it. I call the onChange function from my select box and give the value from the select box to the function.
Code:
function getXMLHTTP()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function getType(categoryName)
{
var strURL="includes/get.php?c="+categoryName+"&sid="+Math.random();
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200)
{document.getElementById('type').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
My second question is, is it possible to send the text between the options tag instead of the value in the options tag?
For your 1st question, I assume your if (req) returns false. Which IE version are you using? Try to add debug codes in getXMLHTTP() function to start diagnosing the codes. Try this solution provided by Microsoft: http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx
I try not to repeat other's answer. Here is the answer for obtaining text in selected option tag : Getting the text from a drop-down box

XML Parsing not working in IE

I am trying to parse a XML file, it works perfectly in FF but dont in IE. Pls help debug this. The code is as follows.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("StepName");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getAttribute("name"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
Your code, improved and annotated:
abstract things like XmlHttp requests into dedicated functions for reusability
always use the var keyword for declaring variables; forgetting this is a source of nasty bugs
use meaningful variable names wherever possible; single-letter names are suitable for loop counters but not for a lot else
never do synchronous HTTP requests, use callbacks instead
functions that do sanity checks first and return early tend to be less deeply nested
do not build HTML with document.write(), use the DOM instead
function getXml(url, onsuccess) {
var xmlhttp;
if (window.XMLHttpRequest) { // IE10+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // IE5 - IE9
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4) return;
if (xmlhttp.statusCode !== 200 || !xmlhttp.responseXML) return;
if (typeof onsuccess !== "function") return;
onsuccess.call(xmlhttp, xmlhttp.responseXML);
};
xmlhttp.send();
}
Now we can use it as follows:
getXml("books.xml", function (xmlDoc) {
var table = e("table", document.body), // see helper function e below
steps = xmlDoc.getElementsByTagName("StepName"),
i, step, tr;
for (i = 0; i < steps.length; i++) {
step = steps[i];
tr = e("tr", table);
e("td", tr, step.getAttribute("name"));
e("td", tr, step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
e("td", tr, step.getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
}
});
// helper function to build HTML elements with the DOM
function e(name, parentNode, text) {
var elem = document.createElement(name),
textProp = elem.hasOwnProperty("textContent") ? "textContent" : "innerText";
if (text) elem[textProp] = text;
if (parentNode && parentNode.appendChild) parentNode.appendChild(e);
return elem;
}
I suspect that your problem lies here:
step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue
Maybe you are making assumptions about the document structure that are incorrect. But unless you post your XML, this is hard to say.
i had similar problem and following code works for all browser ...the trick is use separate code XML for IE browsers or that are version of less than 10 .
so every time Ajax is call a method parseXml is called with input parameter XML Dom or text, depending on browser .... and if current browser is IE, it upload XML doc, process it according to Microsoft standards and return XML and rest of processes in Ajax carries on as expected!!
note : browser.msie is not supported in jQuery 1.9 but you can add jquery-migrate-1.2.1.min.js in order to make it compatible or use userAgent and find which is current browser
$.ajax({
type: 'GET',
url: 'XML_file.xml',
dataType: ($.browser.msie) ? "text" : "xml",
success: function (xml) {
var processedXML = parseXml(xml);
$(processedXML).find('my record').each(function () { //code }
});
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}

Parse XML data on page load & insert into div using AJAX / Javascript

I am working on a page that uses javascript / AJAX to parse xml from a file. I need to be able to parse a url on the loading of a page and insert it into a div. I have the script written but I need help getting 2 things:
1) having it parse an XML file and load that data into a div on page load
2) the option to click a link and load that data into the same div instead of what was there when the page loaded.
I am using an external script to do this & embeded a link to it in my page
HTML example to request data:
<div id="rightcolumn">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>
How do I change that to load #1 when the page loads & #2 when a link is clicked?
For the script, do I need anything special at the top to make sure it loads properly? jQuery has $(document).ready(function() {//GUTS}, do I need something similar with AJAX?
My Script
function loadXMLDoc(url){
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)
{
var anno= xmlhttp.responseXML.documentElement.getElementsByTagName("anno");
// Parser Guts
}
document.getElementById('rightcolumn').innerHTML=txt;
}
}
xmlhttp.open("GET","url",true);
xmlhttp.send();
Usage
<!-- when the user clicks -->
<button onclick="ajax('#ELEMENT','cd_catalog.xml')">Get CD info</button>
// when the page loads
window.onload = function () {
ajax('#ELEMENT', 'cd_catalog.xml');
};
or you can place a script tag at the bottom of the page, or use the dom ready event
Code
function getXmlHttpObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(el, url, onSuccess, onError) {
if (typeof el == "string")
el = document.getElementById(el);
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 ) {
if (el)
el.innerHTML = this.responseText;
if (typeof onSuccess == 'function')
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

Categories