Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

JavaScript Forum


You are currently viewing our JavaScript Forum as a guest. Please register to participate.
Login



Reply
AJAX/JavaScript working in Firefox + Opera, not in IE
Old 08-14-2006, 02:09 PM AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
Hi,

I'm developing a web application and one of the features is an autosave that automatically submits whatever data the form currently holds. It does it silently in the background while the user is still working on the form and they get notified through a message saying "Last AutoSave at: (time)".

This is working fine with Firefox and Opera, yet not Internet Explorer. This is the code:

Code:
<script type="text/javascript" src="ajax.js"></script>

<script type="text/javascript">

var num = 0;
    
function auto_save() {
    num++;
    sub(state);
    window.setTimeout("auto_save()", 30000);
}

</script>

<body onload="auto_save()">
That is basically running the auto save every 30 seconds. The function being called each time is called sub with the argument being the form name (state)

The sub function is part of a JS file called ajax.js

This is the contents of ajax.js:

Code:
    var xmlReq = null;
    
     // Get the XML HTTP request depending on the browser
     function getXML(file,str)

    {

       var doc = null;

       if (window.ActiveXObject)

       {

           doc = new ActiveXObject("Microsoft.XMLHTTP");

           doc.onreadystatechange = displayState;

       }

       else

       {

           doc = new XMLHttpRequest();

           doc.onload = displayState;

       }

       doc.open( "POST", file, true );

       doc.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

       doc.send(str);

       return doc;

    }
    
    // Get all the form values from the specified form
    function getFormValues(fobj) {
        
        var str = "";
        
        for(var i = 0;i < fobj.elements.length;i++) {
            
            switch(fobj.elements[i].type) {
                
                case "text":
                case "textarea":
                case "password":
                
                if (!fobj.elements[i].disabled) { str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&"; }
                
                break;
                
                case "hidden":
                
                //hidden cannot be disabled
                str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&";
               
                 break;
                 
                 case "checkbox":
                 case "radio":
                 
                 if(fobj.elements[i].checked && !fobj.elements[i].disabled) { str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&"; }
                 
                 break;
                 
                 case "select-one":
                 
                 if (!fobj.elements[i].disabled) { str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].options[fobj.elements[i].selectedIndex].value) + "&"; }
                
                 break;
                 
                 case "select-multiple":
                 
                 if (!fobj.elements[i].disabled) {
                     for (var j = 0; j < fobj.elements[i].length; j++) {
                         var optElem = fobj.elements[i].options[j];
                         if (optElem.selected === true) {
                             str += fobj.elements[i].name + "[]" + "=" + encodeURIComponent(optElem.value) + "&";
                         }
                     }
                 }
                 
                 break;
                 
             }
        }
        
        //Strip final &amp;
        str = str.substr(0,(str.length - 1));
        return str;
        
     }
     
     // Output result to browser
     function displayState() {
      
             var res = document.getElementById("last_auto");
             var now = new Date();
             var hour = now.getHours();
             var mins = now.getMinutes();
             var secs = now.getSeconds();
             
             res.innerHTML = "Last AutoSave at: <strong>"+hour+": "+mins+": "+secs+"</strong>";
             res.style.visibility = "visible";
             
      }    
     
    // Gather everything together and submit it
    function sub(f)

    {

       var file = 'auto_save.php';

       var str = getFormValues(f,"validate");

       xmlReq = getXML(file,str);

    }
Is there anything you can spot that will make it not work with IE? If you need any further information from me, just ask.

Thanks in advance.
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
 
Register now for full access!
Old 08-15-2006, 04:32 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
chrishirst's Avatar
Missing! presumed drunk.

Posts: 41,526
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
what versions of IE have you tried ?

you may try something like

Code:
function createRequestObject() {
    var ro;
    /*@cc_on
    @if (@_jscript_version >= 5)
        try {
            ro = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ro = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                ro = false;
            }
        }
    @else
        ro = false;
    @end @*/
    if (!ro && typeof XMLHttpRequest != 'undefined') {
        try {
            ro = new XMLHttpRequest();
        } catch (e) {
            ro = false;
        }
    }
    return ro;
}
above code "borrowed" from Microsoft: Active Server Pages (ASP) - taxi quote system. help needed to reload a page.
__________________
Chris. ->> Links are advertising NOT optimising!! <<-
A foolish consistency is the hobgoblin of little minds
Thought for today:- I SEO the only industry where all the cowboys are Indians?
chrishirst is online now
Reply With Quote
View Public Profile Visit chrishirst's homepage!
 
Old 08-15-2006, 06:05 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
Unfortunately, that didn't work. It also made it not work in Firefox.

Thanks for your help anyway.
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
Old 08-15-2006, 05:08 PM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
Oh, forgot to mention in my last post, the version of IE that i'm using is version 6. I haven't tested it in version 7 yet.
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
Old 08-17-2006, 01:40 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Ultra Talker

Posts: 256
Location: Auckland, New Zealand
Trades: 0
Here's my function for XMLHttpRequest taken out of my class for creating AJAX enabled sites, should work with IE, Mozilla/Firefox, Opera and Gecko based browsers as long as they're quite modern.

Code:
function getXMLHttpRequest()
{
	if(window.XMLHttpRequest)
	{
		return new window.XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		try
		{
			return new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(e1)
		{
			try
			{
				return new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch(e2)
			{
				return null;
			}
		}
		@end @*/
	}
	else if(window.createRequest)
	{
		return new window.createRequest();
	}
	return null;
};
To use it in your code, just replace var doc = null with var doc = getXMLHttpRequest();

You'll also want to make sure you check that it's set, otherwise it should be assumed that browser doesn't support this method, so exiting out of the function would be a good idea.

Code:
if(doc == null) return;
Then you can continue with the things you're doing.

Hopefully that works, if you want me to show you how with your code, then just ask and I'll show you but I think you should be able to work with it now.

Cheers,

MC
__________________
#------------------------------signature---------------------------------------------------------------------------------#
Quote:
I am well recognised for what I don't do than what I do. Chores are just one of those things.
mastercomputers is offline
Reply With Quote
View Public Profile Visit mastercomputers's homepage!
 
Old 08-17-2006, 06:26 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
Thanks for your reply, I tried implementing that in ajax.js but it wouldn't work, not in Firefox either. Could you show me how you would use it with that code please?

Thanks in advance
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
Old 08-18-2006, 12:53 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Ultra Talker

Posts: 256
Location: Auckland, New Zealand
Trades: 0
Hey Cypher,

I'm just posting an example based on your code to show it in action, should work even if the file 'auto_save.php' does not exist. The only problem I did see with your code, is that 'state' was not defined and since this to me was the form, I decided to use that.

Here it is:

HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Form</title>
    <script type="text/javascript">
    /*<![CDATA[*/
      var xmlReq = null;
      var num = 0;

      function getXMLHttpRequest() {
        if(window.XMLHttpRequest) {
          return new window.XMLHttpRequest();
        }
        else if(window.ActiveXObject) {
        /*@cc_on @*/
        /*@if (@_jscript_version >= 5)
          try {
            return new ActiveXObject('Msxml2.XMLHTTP');
          }
          catch(e1) {
            try {
              return new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e2) {
              return null;
            }
          }
        @end @*/
        }
        else if(window.createRequest) {
          return new window.createRequest();
        }
        return null;
      };

      function displayState() {
        var res = document.getElementById('last_auto');
        var now = new Date();
        var hour = now.getHours();
        var mins = now.getMinutes();
        var secs = now.getSeconds();

        res.innerHTML = 'Last AutoSave at: <strong>'+hour+':'+mins+':'+secs+'</strong>';
        res.style.visibility = 'visible';
      }

      function getXML(file,str) {
        var doc = getXMLHttpRequest();
        if(doc == null) {
          return;
        }
        doc.onreadystatechange = displayState;
        doc.open('POST',file,true);
        doc.setRequestHeader('Content-Type','application/x-www-form.urlencoded; charset=UTF-8');
        doc.send(str);
        return doc;
      }

      function getFormValues(fobj) {
        var str = '';
        for(var i = 0, j = fobj.elements.length; i < j; i++) {
          switch(fobj.elements[i].type) {
            case 'text':
            case 'textarea':
            case 'password':
              if(!fobj.elements[i].disabled) {
                str+=fobj.elements[i].name+'='+encodeURIComponent(fobj.elements[i].value)+'&';
              }
              break;
            case 'hidden':
              str+=fobj.elements[i].name+'='+encodeURIComponent(fobj.elements[i].value)+'&';
              break;
            case 'checkbox':
            case 'radio':
              if(fobj.elements[i].cheched && !fobj.elements[i].disabled) {
                str+=fobj.elements[i].name+'='+encodeURIComponent(fobj.elements[i].value)+'&';
              }
              break;
            case 'select-one':
              if(!fobj.elements[i].disabled) {
                str+=fobj.elements[i].name+'='+encodeURIComponent(fobj.elements[i].options[fobj.elements[i].selectedIndex].value)+'&';
              }
              break;
            case 'select-multiple':
              if(!fobj.elements[i].disabled) {
                for(var k = 0, l = fobj.elements[i].length; k > l; j++) {
                  var optElem = fobj.elements[i].options[j];
                  if(optElem.selected === true) {
                    str+=fobj.elements[i].name+'[]='+encodeURIComponent(optElem.value)+'&';
                  }
                }
              }
              break;
          }
        }
        str = str.substr(0,(str.length - 1));
        return str;
      }

      function sub(f) {
        var file = 'auto_save.php';
        var str = getFormValues(f, 'validate');
        xmlReq = getXML(file,str);
      }

      function auto_save() {
        num++;
        sub(document.getElementById('state'));
        window.setTimeout('auto_save()',30000);
      }
    /*]]>*/
    </script>
  </head>
  <body onload="auto_save();">
    <form id="state" name="state" action="" method="POST">
      <fieldset>
        <legend>Basic Form</legend>
        <input id="fname" name="fname" type="text" /><br />
        <input id="submit" name="submit" type="submit" value="Submit" />
      </fieldset>
    </form>
    <p id="last_auto"></p>
  </body>
</html>
Hopefully that helps you.

Cheers,

MC
__________________
#------------------------------signature---------------------------------------------------------------------------------#
Quote:
I am well recognised for what I don't do than what I do. Chores are just one of those things.

Last edited by mastercomputers; 08-18-2006 at 10:35 PM..
mastercomputers is offline
Reply With Quote
View Public Profile Visit mastercomputers's homepage!
 
Old 08-18-2006, 06:57 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
Thanks for your reply and the time you took to help me. Unfortunately, that didn't work either. I'm positive auto_save.php works as it is a copy of the form processor for a normal form submit.

I'm basing the code of this article: XML in the Browser: Submitting forms using AJAX

That code runs when it is called by the press of a button. I modified it slightly to make it run every 30 seconds (i.e an autosave)

Would you recommend anything else to use as an autosave? Or is there anything else I can do to the current code?
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
Old 08-18-2006, 10:30 PM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Ultra Talker

Posts: 256
Location: Auckland, New Zealand
Trades: 0
Hey Cypher,

I'm a bit confused as to why it's not working for you, as I've tested the above (in IE and FF) and verified it actually works as intended except the problem may lie in your auto_save.php if you're testing to see if any entries were entered?

There is no need to press the button for it to work, it should work upon first page load and then each timeout.

I made sure the XMLHttpRequest actually sends the data of the form so this is working fine.

So I have to ask, how are you verifying if this works?

Is it possible to see the auto_save.php file, since this is probably where the problem lies.

Cheers,

MC
__________________
#------------------------------signature---------------------------------------------------------------------------------#
Quote:
I am well recognised for what I don't do than what I do. Chores are just one of those things.
mastercomputers is offline
Reply With Quote
View Public Profile Visit mastercomputers's homepage!
 
Old 08-19-2006, 05:28 AM Re: AJAX/JavaScript working in Firefox + Opera, not in IE
Cypher_489's Avatar
Skilled Talker

Posts: 81
Name: Callum
Location: England
Trades: 0
What I meant with the button was that the script originally called the function from a button press. Instead, I removed that and made the function run every 30 seconds.

It's also confusing me as I've tried several different ways and I did it exactly as you posted it before.

Anyway, here's auto_save.php (It's integrated with Vbulletin):

PHP Code:
<?php 

    
require_once('includes/global.php');
    require_once(
'includes/functions_user.php'); 

    
// Include DB connection file
    
include("db.php");
    
    
// If this is accessed by a user, redirect to homepage
    
if (stristr(htmlentities($_SERVER['PHP_SELF']), "auto_save.php")) {
        
Header("Location: index.php");
        die();
    }
    
    
// Get the logged in username 
    
$preuname $vbulletin->userinfo['username'];
    
$illegal_chars = array( ' ''.''@' );
    
$uname str_replace($illegal_chars'_'$preuname); 
    
    
// Query the logged in users sites
    
$query_sites mysql_query"SELECT * FROM dt_sites WHERE uname = '$uname'" );
    
// Fetch the logged in users sites
    
$fetch_sites mysql_fetch_array($query_sites);
    
    
// If there is a site cookie, use it. Else, use the first one in the DB
    
if( isset($_COOKIE['twtselectedsite']) ) {
    
$site $_COOKIE['twtselectedsite']; }
    else { 
$site $fetch_sites['site_url']; }
    
    
// Get the logged in sites number
    
$query_site_number mysql_query"SELECT site_number FROM dt_sites WHERE uname = '$uname' AND site_url = '$site'" );
    
$fetch_site_number mysql_fetch_array($query_site_number);

    
$site_number $fetch_site_number['site_number'];
    
$prefix "dt_";        
    
$k "state";
    
            
// Create array of MySQL queries
            
$arr = array();
            
$sql mysql_query("SELECT * FROM dt_directories") or die(mysql_error()); 
            
$d mysql_num_rows($sql);
            for( 
$i 1$i <= $d$i++ ) {
                 
$state $_POST["$k$i"];
                 if( !empty(
$state) ) { 
                 
$arr$i ] = "UPDATE " $prefix $uname " SET `$site_number` = '$state' WHERE did = '$i'";  } }
                                
                 foreach( 
$arr as $mysql ) {
                 
mysql_query"$mysql);
                 }
                 
?>
__________________
Cypher_489


Please login or register to view this content. Registration is FREE
- Collection of tech tips, scripts and guides.
Please login or register to view this content. Registration is FREE

Last edited by Cypher_489; 08-21-2006 at 01:10 PM..
Cypher_489 is offline
Reply With Quote
View Public Profile Visit Cypher_489's homepage!
 
Reply     « Reply to AJAX/JavaScript working in Firefox + Opera, not in IE
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.32894 seconds with 12 queries