SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Apr 2003
    Posts
    332
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    script runs once in IE then stops

    Hi,

    I have a short ajax script running OK in FF. In IE, it runs once correctly then will not repeat unless I refresh the page.

    html:
    Code:
    <body>
    <div id="container">
    <h1>Agencies</h1>
    <div id="intro">
    <p>You are invited.</p>
    </div><!-- end div intro -->
    <div id="input">
    <form id="providerreport" method="post" action="report.php">
    <?php
    echo "<p><label class='lab' for='age'>Age:</label> <select id='age' name='age' style='width:14em'><option value=''>View All</option>";
    include("conn.php");
    $rs=mysql_select_db("",$conn) or die('Could not connect: ' . mysql_error());
    $sql="select DISTINCT age FROM comresource";
    $rs=mysql_query($sql,$conn);
    while($row=mysql_fetch_array($rs)){
    echo("<option value= '" . $row['age'] . "'>" . $row['age'] . "</option>");
    	}
    echo "</select></p>";
    ?>
    <p style="text-align:center"><input type="submit" value="View Information"></p>
    </form>
    </div><!-- end div input -->
    <div id="info">&nbsp;</div><!-- end div info -->
    <hr>
    </div><!-- end div container -->
    </body>
    The js file:
    Code:
    function createXHR(){
    var request = false;
    try{
    	request = new ActiveXObject('Msxml2.XMLHTTP');
    	}
    catch(err2){ 
    	try{	
    		request = new ActiveXObject('Microsoft.XMLHTTP');
    		}
    	catch(err3){
    			try{
    				request = new XMLHttpRequest();
    				}
    			catch (err1){
    					request = false;
    					}
    					if(request == false){
    					alert("Error creating request object!");
    				}
    			}
    		}
    		return request;
    	}
    window.onload=init;
    function init(){
    var requestResponse = "";
    var request=createXHR();
    	if(request){		
    		if(document.getElementById("info")){
    			document.getElementById("providerreport").onsubmit=function(){
    			request.onreadystatechange=function(){
    	if(request.readyState==4){
    		if(request.status==200){
    			requestResponse=request.responseText;
    			parseResponse();
    			}
    		else{alert("Error posting to file " + request.statusText);
    			}
    		}
    	}
    var nform=document.forms[0];
    var age=nform['age'].value;
    var infoStr="age=" + escape(age);
    var url="agencyreport.php";
    request.open("POST",url,true);
    request.setRequestHeader ("Content-type","application/x-www-form-urlencoded");
    request.send(infoStr);
    return false;	
    }
    }
    function parseResponse(){
    	var nMessage = document.getElementById("info")
    	nMessage.style.display="block";
    	nMessage.innerHTML=requestResponse;
    }
    }
    }
    The php file:
    Code:
    <?php
    echo "<p>Filters applied:<ul><li>" . $_POST['age'] . "</li></ul></p>";
    include("conn.php");
    $rs=mysql_select_db("",$conn) or die('Could not connect: ' . mysql_error());
    $age = mysql_real_escape_string($_POST['age']);
    if(isset($age) && ($age!=='')) {
    $sql="SELECT * FROM comresource WHERE age='$age' ORDER BY name";
    	}
    else{
    	$sql="SELECT * FROM comresource ORDER BY name";
    	}
    $rs=mysql_query($sql,$conn) or die("Query Failed  112 " . mysql_error() . "<br>" . mysql_errno());
    $num = mysql_num_rows($rs);
    if($num==0){
    echo ("No Match to Your Request");
    die();	
    }
    elseif($num>0){
    echo ("Number of records returned " . $num);
    }
    while($row=mysql_fetch_array($rs)){
    	$name=$row["name"];
    	$service=$row["service"];
    	$age=$row["age"];
    	echo "<div class='agency'><p><span class='propname'>" . $row['name'] . "</span><br>Service:&nbsp;" . $row['service'] . "<br>Client Age:&nbsp;" . $row['age'] .  "</a></p></div>"; 
    }
    ?>
    I sure could use some help.

    Thanks,

    Andy

  2. #2
    Google Engineer polvero's Avatar
    Join Date
    Oct 2003
    Location
    Mountain View
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It looks like you need a little cleanup with the way you're handling Ajax. Consider an approach like this:

    Code:
    var asyncRequest = function() {
      function handleReadyState(o, callback) {
        if (o && o.readyState == 4 && o.status == 200) {
          if (callback) {
            callback(o);
          }
        }
      }
      var getXHR = function() {
        var http;
        try {
          http = new XMLHttpRequest;
            getXHR = function() {
              return new XMLHttpRequest;
            };
        }
        catch(e) {
          var msxml = [
            'MSXML2.XMLHTTP.3.0',
            'MSXML2.XMLHTTP’,
            'Microsoft.XMLHTTP’
          ];
          for (var i=0, len = msxml.length; i < len; ++i) {
            try {
              http = new ActiveXObject(msxml[i]);
              getXHR = function() {
                return new ActiveXObject(msxml[i]);
              };
              break;
            }
            catch(e) {}
          }
        }
        return http;
      };
      return function(method, uri, callback, postData) {
        var http = getXHR();
        http.open(method, uri, true);
        handleReadyState(http, callback);
        http.send(postData || null);
        return http;
      };
    }();
    Usage:
    Code:
    asyncRequest('POST', 'test.php', function(o) {
      alert(o.responseText);
    });
    Also consider moving your init off the onload handler, and add it as an event listener...

    Code:
    var addEvent = function() {
      if (window.addEventListener) {
        return function(el, type, fn) {
          el.addEventListener(type, fn, false);
        };
      } else if (window.attachEvent) {
        return function(el, type, fn) {
          var f = function() {
            fn.call(el, window.event);
          };
          el.attachEvent('on' + type, f);
        };
      }
    }();
    Usage:
    Code:
    addEvent(window, 'load', init);
    That way you won't collide with anything else you need to add to your init stack.

  3. #3
    SitePoint Addict
    Join Date
    Apr 2003
    Posts
    332
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That is beautiful code! It will take me time to digest it.



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •