Jump to content

Problem Onload Ajax Functions And A Function Working In Reverse!


jsatan

Recommended Posts

Hi all. I'm new to AJAX and JS, I've coded in other languages and thought I'd have a bash at this:So to the point: I have the following issues:1. In the code there's a function called "update": This function is called onload generated from the PHP backend. This function is to loop at a set interval and update the page:You will notice that this updater first calls a function calls getGame: This function gets the current game using ajax and then generates a table output from the results. The second function (currenly in a setTimer) is getSubmissionUpdates. The problem I have is:If I comment out getSubmissionUpdates so that function isnt run the page will load fine and display a table output of the first function call getGame. This works fine, but no updates will be recieved (as they're not being checked for.If I have the getSubmissionUpdates function not in the setTimer and allow it to run in due time nothing is displayed on the page: My temp work around was to place this function call in a timer so "spread" out the AJAX calls to the server. Works fine but I'd like to know why this is. Given that I'm using the work around I've continued coding (just for fun really) and created two functions that fade in and out a DIV area (fadeIn, fadeOut): these work fine, tested using buttons and text on a simple page:These are to be used when the getSubmissionUpdate is being run: I place a call to the fadeOut function then update the DIV and then fadeIn the new update. I've commented out the fadeOut call in function proccessSubmissionUpdates for the time being. The problem I'm having (apart from these fade function don't work with IE8) is that even tho the fadeOut function is called first it happens after the DIV update!I'm lost as to why this happens:I know the code is long, I've cut out a few functions that started from buttons as anything done this way works fine without a hitch:Please feel free to slate my code and provide feedback. It's the only way I'll learn after all. :) PS this JS is loaded in the header of the page. Any questions please ask.

var xmlhttp;var cSub_id = 0;var first_sub_id = 0;var cGame_change_id = 'new';var wTimer;var mTimer;var cGameID;function GetXmlHttpObject(){  if (window.XMLHttpRequest){    // code for IE7+, Firefox, Chrome, Opera, Safari    return new XMLHttpRequest();  }  if (window.ActiveXObject){    // code for IE6, IE5    return new ActiveXObject("Microsoft.XMLHTTP");  }return null;}function setAppState(sub_ID, newState){  xmlhttp=GetXmlHttpObject();  if (xmlhttp==null){    alert ("Browser does not support HTTP Request");    return;  }  var url="ajax_getset_subs.php";  url=url+"?sub_id="+sub_ID;  url=url+"&new_approval_state="+newState;  url=url+"&rnd="+Math.random();  xmlhttp.onreadystatechange=function (){    if (xmlhttp.readyState==4){     	var view_game = document.getElementById("sub_app_state_"+sub_ID);		  var xmldoc = xmlhttp.responseXML;		  var sub_nodes = xmldoc.getElementsByTagName("sub"); 		  var n_sub = sub_nodes.length		  		  for (i = 0; i < n_sub; i++) {        var approval_state_node = sub_nodes[i].getElementsByTagName("approval_state");        var out_app_state = approval_state_node[0].firstChild.nodeValue;		  }        view_game.innerHTML = setAppColour(out_app_state);               }  };xmlhttp.open("GET",url,true);xmlhttp.send(null);}function setGameState(game_ID, appState, showRuleState){  xmlhttp=GetXmlHttpObject();  if (xmlhttp==null){    alert ("Browser does not support HTTP Request");    return;  }  var url="ajax_set_game_state.php";  url=url+"?game_id="+game_ID;  url=url+"&game_state="+appState;  url=url+"&rule_state="+showRuleState;  url=url+"&rnd="+Math.random();  xmlhttp.onreadystatechange=function (){    if (xmlhttp.readyState==4){       document.getElementById("game_state").innerHTML=xmlhttp.responseText;    }  };xmlhttp.open("GET",url,true);xmlhttp.send(null);		}function getGame() {  xmlhttp=GetXmlHttpObject();  if (xmlhttp==null){    alert ("Browser does not support HTTP Request");    return;  }  var url="ajax_get_game.php";  url=url+"?game_id="+cGameID;  url=url+"&last_id="+cSub_id;  url=url+"&rnd="+Math.random();  xmlhttp.onreadystatechange=renderGameResponse;      xmlhttp.open("GET",url,true);xmlhttp.send(null);		}function renderGameResponse(){		if (xmlhttp.readyState==4){		  var xmldoc = xmlhttp.responseXML;		  var sub_nodes = xmldoc.getElementsByTagName("entry"); 		  var n_sub = sub_nodes.length;		  if(n_sub == 0 && cSub_id == 0){        document.getElementById("DIV_system_message").innerHTML = "No Submissions to display, why not add one?";      }else{        document.getElementById("DIV_system_message").innerHTML = " ";      }           		    for (i = 0; i < n_sub; i++) {		      		      var sub_id_node         = sub_nodes[i].getElementsByTagName("sub_id");          var user_id_node        = sub_nodes[i].getElementsByTagName("user_id");          var game_id_node        = sub_nodes[i].getElementsByTagName("game_id");          var submission_node     = sub_nodes[i].getElementsByTagName("submission");          var approval_state_node = sub_nodes[i].getElementsByTagName("approval_state");          var admin_state_node    = sub_nodes[i].getElementsByTagName("admin_state");                    var out_sub_id          = sub_id_node[0].firstChild.nodeValue;          var out_user_id         = user_id_node[0].firstChild.nodeValue;           var out_game_id         = game_id_node[0].firstChild.nodeValue;          var out_submission      = submission_node[0].firstChild.nodeValue;          var out_app_state       = approval_state_node[0].firstChild.nodeValue;          var out_admin_state     = admin_state_node[0].firstChild.nodeValue;                   createTableEntry(out_sub_id, out_user_id, out_game_id, out_submission, out_app_state, out_admin_state);          cSub_id = out_sub_id;                       }    }   }function addSubmission(){  if (document.getElementById('ajax_input').value == ""){      document.getElementById("DIV_system_message").innerHTML= "Your entry was empty, try again.";  }else{    var submission = document.getElementById('ajax_input').value;    document.getElementById("ajax_input").value = "";    xmlhttp=GetXmlHttpObject();    if (xmlhttp==null){      alert ("Browser does not support HTTP Request");      return;    }    var url="ajax_new_submission.php";    url=url+"?game_id="+cGameID;    url=url+"&submission="+submission;    url=url+"&rnd="+Math.random();    xmlhttp.onreadystatechange=function (){      if (xmlhttp.readyState==4){         document.getElementById("DIV_system_message").innerHTML= "System updating, Please wait";      }    };  xmlhttp.open("GET",url,true);  xmlhttp.send(null);  }	}function update(in_game_id){  cGameID = in_game_id;  getGame();    wTimer = setTimeout('getSubmissionUpdates()',3000);  clearInterval(mTimer);  var delay = function (){update(cGameID); };  mTimer = setTimeout(delay,5000);}function getSubmissionUpdates(){  xmlhttp=GetXmlHttpObject();   if (xmlhttp==null){    alert ("Browser does not support HTTP Request");    return;  }  var url="ajax_get_changes.php";  url=url+"?game_id="+cGameID;  url=url+"&change_id="+cGame_change_id;  url=url+"&rnd="+Math.random();  xmlhttp.onreadystatechange=proccessSubmissionUpdates;xmlhttp.open("GET",url,true);xmlhttp.send(null);}function proccessSubmissionUpdates(){    if (xmlhttp.readyState==4){    var xmldoc = xmlhttp.responseXML;		var sub_nodes = xmldoc.getElementsByTagName("entry");   		var n_sub = sub_nodes.length;				if (cGame_change_id == 'new'){                       cGame_change_id = sub_nodes[0].getElementsByTagName("change_id")[0].firstChild.nodeValue;                              }else{        		  for (i = 0; i < n_sub; i++) {				            var change_id_node      = sub_nodes[i].getElementsByTagName("change_id");        var sub_id_node         = sub_nodes[i].getElementsByTagName("sub_id");        var approval_state_node = sub_nodes[i].getElementsByTagName("approval_state");                  var out_sub_id          = sub_id_node[0].firstChild.nodeValue;        var out_change_id       = change_id_node[0].firstChild.nodeValue;        var out_approval_state   = approval_state_node[0].firstChild.nodeValue;         //fadeOut(out_sub_id);        document.getElementById('sub_app_state_'+out_sub_id).innerHTML = setAppColour(out_approval_state);                cGame_change_id = out_change_id;      }                     }   }}function createTableEntry(in_sub_id, in_user_id, in_game_id, in_submission, in_app_state, in_admin_state){  var table = document.getElementById('new_div_table_2');  var tr2   = document.createElement('TR');  var td1   = document.createElement('TD');  var td2   = document.createElement('TD');  var td3   = document.createElement('TD');  var td4   = document.createElement('TD');  var td5   = document.createElement('TD');  var td6   = document.createElement('TD');   var divTag = document.createElement("div");  var but1   = document.createElement("INPUT")  var but2   = document.createElement("INPUT")     but1.type = "button";  but1.value = "Reject";  but1.onclick = function(){setAppState(in_sub_id, '1')};  but2.type = "button";  but2.value = "Approve";  but2.onclick = function(){setAppState(in_sub_id, '2')};                     divTag.id = 'sub_app_state_'+in_sub_id;            td1.innerHTML = in_sub_id;  td2.innerHTML = in_user_id;  td3.innerHTML = in_game_id;  td4.innerHTML = in_submission;  divTag.innerHTML = setAppColour(in_app_state);          table.appendChild(tr2);    tr2.appendChild(td1);  tr2.appendChild(td2);  tr2.appendChild(td3);  tr2.appendChild(td4);  tr2.appendChild(td5);        td5.appendChild(divTag);  if(in_admin_state == 'yes'){     tr2.appendChild(td6);    td6.appendChild(but1);    td6.appendChild(but2);  }}function setAppColour(in_app_state){  if(in_app_state == '0'){    return '<b><font size="4" color=3399FF>Pending</font></b>';  }else if (in_app_state == '1'){    return '<b><font size="4" color=FF0000>Rejected</font></b>';      }else {    return '<b><font size="4" color=00CC00>Approved</font></b>';  }}function alertMe(in_alert){  alert(in_alert);}function setOpacity(eid, level) {  document.getElementById('sub_app_state_'+eid).style.opacity = level;  document.getElementById('sub_app_state_'+eid).style.MozOpacity = level;  document.getElementById('sub_app_state_'+eid).style.KhtmlOpacity = level;  document.getElementById('sub_app_state_'+eid).style.filter = "alpha(opacity=" + (level * 100) + ");";}var duration = 1000;  /* 1000 millisecond fade = 1 sec */var steps = 20;       /* number of opacity intervals   */function fadeIn(eid){  for (i = 0; i <= 1; i += (1 / steps)) {    setTimeout("setOpacity("+eid+"," + i + ")", i * duration);  }}function fadeOut(eid) {  for (i = 0; i <= 1.1 ; i += (1 / steps)) {    setTimeout("setOpacity("+eid+"," + (1 - i) + ")", i * duration)  }}

Link to comment
Share on other sites

I haven't read through all of the code, but you're using a global variable to hold your XHR object which you use every time you send an ajax request. That means that sending one request while you're waiting for another one to come back will overwrite the first one. Instead of using a global variable you need each request to use its own XHR object.

Link to comment
Share on other sites

Now you've told me it clear:lol. Crasy. So that's one problem down. Thank you very much, even tho it's a small thing it helps:I've had to keep a them as gobal but just made 6 of them, as you can see some of the ajax requests call another function when ready, to pass this information they need to be global:Any ideas on the backwards function?Thanks again for this. I was pulling ym hair out over it... :)

Link to comment
Share on other sites

They don't need to be global, you can use a function closure instead of named functions. Look at how setAppState uses onreadystatechange compared to getGame. setAppState uses a closure, getGame does not.
Indeed, The global is only for testing at the moment, I'll sort them out to be just like setAppState in morning, :)Cheers for pointing this out, I was aware of it....Jon.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...