Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pausing javascript during ajax processing 1

Status
Not open for further replies.

LarrySteele

Programmer
May 18, 2004
318
US
I used the ajax tutorial from w3schools and have successfully implemented a couple of ajax lookups. While somewhat straightforward, the process is not without quirks. I'm using the following code to lookup a person based on the id entered in a textbox:
Code:
function find_manager() {
    var var_mgr_id = document.calform.var_superv_id.value;

    seekMgr(var_mgr_id);
    [!]// alert('pause goes here');[/!]
    var mgr_first_name = document.getElementById('inp_mgr_first_name').value;
    alert('Manger\'s first name is: ' + mgr_first_name);
    }

Note the commented alert. If I uncomment the alert statement and let it run, the manager's name gets filled in the text box as desired. However, if I leave the alert commented so that it does not run, then I get an Object Expected error. In short, what appears to be happening is that this javascript needs to pause long enough for seekMgr to run. Putting in an alert is one way to do it. I'm sure there's a better way to do this, but I've hit a wall and haven't been able to locate a solution - yet.

Here is my javascript:
Code:
var xmlHttp

function seekMgr(str) {
	if (str.length != 8) {
        document.getElementById("txt_mgr_results").innerHTML=''
		return;
	}
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request")
        return
        }

    var url="ajax/getmanager.cfm"
    url=url+"?q="+str
    url=url+"&sid="+Math.random()
    xmlHttp.onreadystatechange=stateChanged_mgr
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
    }

function stateChanged_mgr() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
        //alert('state change')
        document.getElementById("txt_mgr_results").innerHTML=xmlHttp.responseText
        //alert(xmlHttp.responseText)
        }
    }

function GetXmlHttpObject() {
    var objXMLHttp=null
    if (window.XMLHttpRequest) {
        objXMLHttp=new XMLHttpRequest()
        }
    else if (window.ActiveXObject) {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
        }
    return objXMLHttp
    }

Here's ajax/getmanager.cfm that fetches the manager's information:

Code:
<cfquery name="qry_mgr"
         datasource="#mydata#"
         username="#myuser#"
         password="#mypw#">

    select last_name,
           first_name
    from mytable
    where id= '#url.q#'
</cfquery>

<cfif qry_mgr.recordcount eq 0>
    <cfoutput>
        <input type="hidden" name="inp_mgr_first_name" value="">
        <input type="hidden" name="inp_mgr_last_name" value="">
    </cfoutput>
<cfelse>
    <cfoutput query="qry_mgr">
        <input type="hidden" name="inp_mgr_first_name" value="#first_name#">
        <input type="hidden" name="inp_mgr_last_name" value="#last_name#">
    </cfoutput>
</cfif>

Again, this works flawlessly, but only as long as I have that alert between seekMgr() and actually using the input element that my ajax creates/fills.

Any assistance/suggestions are most appreciated.

- Larry
 
I found a solution: split the function into two and call the second from the first via setTimout:

Code:
function find_manager() {
    var var_mgr_id = document.calform.var_superv_id.value;

    seekMgr(var_mgr_id);
    setTimeout('fill_manager();',500);
    }

function fill_manager() {
    var mgr_first_name = document.getElementById('inp_mgr_first_name').value;
    alert('Manger\'s first name is: ' + mgr_first_name);
    }

This works in that there's enough pause between the two processes that the element is created and filled before it's called. I tested this a few times. It ran fine as low as 25ms. It bombed when I dropped it to 20ms.

Is it me, or is this a really cludgy solution?

- Larry
 
rather than a set timeout I pass the ajax call the name of the function I want called once it has finished.
this is my ajax code
Code:
    var http_request = false;
    var myfunc;
    function makeRequest(url, parameters, func) {
        http_request = false;
        myfunc = func;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            //if (http_request.overrideMimeType) {
             //   http_request.overrideMimeType('text/xml');
                // See note below about this line
            //}
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('AJAX - Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-[URL unfurl="true"]www-form-urlencoded");[/URL]
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
      
    }

    function alertContents() {

        if (http_request.readyState == 4) {
            if(http_request.status && http_request.status == 200) {
                [b]// Call return function
               myfunc(http_request.responseText); [/b]  
                                            
            } else {
                alert(http_request);
                alert(http_request.status);
                alert('There is a problem with AJAX, please contact support.');
                
            }
        }
    }

and I call the ajax like so
Code:
    // call ajax
    makeRequest('[URL unfurl="true"]http://www.yourdomain.co.uk/yourprogram','URLVARS',disp_league);[/URL]

so basicaly once the ajax content is retrieved it will run my function disp_league.



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Thanks for the suggestion. However, your solution would still require me to keep my single function find_manager() split in two: find_manager() and fill_manager() as in my solution. Find_manager() would call the ajax functions and ajax would then call fill_manager(). I was hoping to avoid having find_manager() split at all. There is one advantage to your suggestion and that is that I don't have to worry about a system glitch that would require a slightly longer delay since yours waits until the operation is complete before calling, while mine waits a set time before moving forward. That means that if there's a system glitch that would need a little more time to complete the process, mine would fail and yours would gracefully wait and complete when ready.

Thanks againg for the suggestion.
Larry
 
I have been told that
Code:
xmlHttp.open("GET",url,true)

the true means Asyncronous and changing it to false means Syncronous so the script making the ajax call would not continue until the ajax request had completed, but I haven't been able to get it to work,it might be an avenue for you to concider though.

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Well now...

Here it is from the horse's mouth (
If the async flag is set to false, then the method must not return until the request has completed. Otherwise, it must return immediately.
[/qoute]
It took a bit to find that snippet because it's not included with the open method as I had expected, but with the send method.

Anyway, I've tested this a few times and so far things seem to be in good shape. I'll try a few more times throughout the day to confirm. Otherwise, you may have found the right answer to my problem.

Thanks!@
Larry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top