Page 1 of 3 123 LastLast
Results 1 to 10 of 23

Thread: Ajax

  1. #1
    Join Date
    May 2006
    Location
    Sydney, Australia - Near the coast.
    Posts
    1,995
    Thanks
    0
    Thanked 8 Times in 7 Posts

    Default Ajax

    Ajax

    This tutorial will help you learn about ajax, which basically retrieves data from another page without refreshing the current page.

    If you want to learn about the history of ajax, what it stands for, then look here. This will just help you actually create an ajax request.

    There will be a code sample at the end, but if you want to learn more than I suggest you follow the step-by-step instructions.

    We'll start with creating a function.
    Code:
    function makeRequest(url, id) {
    And define http_request...
    Code:
    	var http_request = false;
    And then create a request function for Mozilla, Safari etc.
    Code:
    		if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    			http_request = new XMLHttpRequest();
    				if (http_request.overrideMimeType) {
    					http_request.overrideMimeType('text/xml');
    				}
    And then create an ActiveXObject for Internet Explorer
    Code:
    		} else if (window.ActiveXObject) { // IE
    			try {
    				http_request = new ActiveXObject("Msxml2.XMLHTTP");
    			} catch (e) {
    				try {
    					http_request = new ActiveXObject("Microsoft.XMLHTTP");
    				} catch (e) {}
    			}
    		}
    And check if the request is created or give an alert and terminate the script
    Code:
    	if (!http_request) {
    		alert('Error creating XMLHttpRequest()');
    		return false;
    	}
    Then checking if the information is recieved from the server yet or else give a "Loading..." message
    Code:
    	http_request.onreadystatechange = function() {
    		var e = document.getElementById(id)
    		if (http_request.readyState == 4 && http_request.status == 200)	{
    			e.innerHTML = http_request.responseText
    		}
    		else	e.innerHTML = "Loading..."
    	};
    Then requesting the URL to the server
    Code:
    	http_request.open('GET', url, true);
    	http_request.send(null);
    GET - For URLs that don't need to send POST data
    POST - For URLs that do need to send POST data
    You need to send data using http_request.send(mydata) with POST, and leave it as null when sending data with GET

    Finally then closing the function
    Code:
    }
    And here's the final script.

    Code:
    <script type="text/javascript">
    function makeRequest(url, id) {
    	var http_request = false;
    		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('Error creating XMLHttpRequest()');
    		return false;
    	}
    	
    	http_request.onreadystatechange = function() {
    		var e = document.getElementById(id)
    		if (http_request.readyState == 4 && http_request.status == 200)	{
    			e.innerHTML = http_request.responseText
    		}
    		else	e.innerHTML = "Loading..."
    	};
    	http_request.open('GET', url, true);
    	http_request.send(null);
    }
    </script>
    There are many uses for Ajax, eg. Google Docs, This "Quick Reply" thing at the bottom etc.

    Have fun using ajax!

    Note - There might be errors in this document, please PM me if you want to report an error, not a question.
    Last edited by tech_support; 04-18-2007 at 11:08 AM.
    Peter - alotofstuffhere[dot]com - Email Me - Donate via PayPal - Got spare hardware? Donate 'em to me :) Just send me a PM.
    Currently: enjoying the early holidays :)
    Read before posting: FAQ | What you CAN'T do with JavaScript | Form Rules | Thread Title Naming Guide

  2. #2
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,626
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    First of all it is a good effort from your side (it always very difficult to write tutorials/articles/books in my opinion), thanks a lot for the ajax introduction.

    There are some points I want to point out about the tutorial.

    1. If a novice developer tries to get a overview of Ajax this will not provide that perfectly (unfortunate)

    2. It is because you've omiited any reference to the server-side processing at all. A novice might be thinking what really happens in the server-side when it invokes the page via ajax function call. You could've extended your example a bit so that it gives an idea about the page's server-side processing from which it gets the data.

    It's so easy that even pcbrainbuster can do it
    You could've avoided this too.

    These are my personal opinions.

    regards

  3. #3
    Join Date
    May 2006
    Location
    Sydney, Australia - Near the coast.
    Posts
    1,995
    Thanks
    0
    Thanked 8 Times in 7 Posts

    Default

    1. If a novice developer tries to get a overview of Ajax this will not provide that perfectly (unfortunate)
    2. It is because you've omiited any reference to the server-side processing at all. A novice might be thinking what really happens in the server-side when it invokes the page via ajax function call. You could've extended your example a bit so that it gives an idea about the page's server-side processing from which it gets the data.
    Hmm... How would I explain that?
    it's so easy that even pcbrainbuster can do it
    You could've avoided this too.
    Ha. Consider it edited.
    Peter - alotofstuffhere[dot]com - Email Me - Donate via PayPal - Got spare hardware? Donate 'em to me :) Just send me a PM.
    Currently: enjoying the early holidays :)
    Read before posting: FAQ | What you CAN'T do with JavaScript | Form Rules | Thread Title Naming Guide

  4. #4
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,626
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    Hmm... How would I explain that?
    Use some server-side script PHP will do the trick. Just make a simple example that gives you the server time in a form field using ajax.

  5. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,000
    Thanks
    44
    Thanked 3,198 Times in 3,160 Posts
    Blog Entries
    12

    Default

    I don't think you should worry about explaining everything. This is just a bootstrap bit of code to do the deed. I added my thanks above as, it saved me some time trying to come up with it on my own.

    I do have a question about:

    Code:
    http_request.overrideMimeType('text/xml');
    // See note below about this line
    I looked over it a few times and saw no explanation and am curious. I get the general idea, but does this force text/xml, or override it? I'm guessing it overrides it.

    Also, I added a little code to my 'clip' of this routine:

    Code:
    function makeRequest(url, id) {
    var http_request = false;
    if (window.XMLHttpRequest&&(!window.ActiveXObject||/http/.test(window.location.href))) { // Mozilla, Safari, IE 7 live...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
    http_request.over . . .
    This allows IE 7 to follow the window.ActiveXObject path locally while using the more efficient window.XMLHttpRequest live. I did this because IE 7 will try to follow the window.XMLHttpRequest path locally, but cannot, due to security restrictions. At least that's a problem in IE 7 with the DD scripts that use a similar type of request test scheme, and I saw no reason why it wouldn't be here, although I might be mistaken.

    And:

    Code:
    if (http_request.readyState == 4 && (http_request.status == 200||!/http/.test(window.location.href)))	{
    I'm not sure if this was necessary, but thought it might be for local testing, doesn't hurt as far as I can tell.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  6. #6
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by tech_support View Post
    We'll start with creating a function.
    I can't say that I really like the way you create the object. The comments are superfluous and inaccurate, too: IE also uses the first code branch.

    I would start by separating the creation part from the rest of the code:

    Code:
    function getRequestObject() {
        var object = null;
    
        if ((typeof XMLHttpRequest == 'object') || (typeof XMLHttpRequest == 'function'))
            object = new XMLHttpRequest();
        else if ((typeof createRequest == 'object') || (typeof createRequest == 'function'))
            object = createRequest();
        else if (typeof ActiveXObject == 'function') {
            /*@cc_on @*/
            /*@if(@_jscript_version >= 5)
            try {
                object = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(e) {
                try {
                    object = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(e) {
                    object = null;
                }
            }
            @end @*/
        }
        return object;
    }
    This adds support for ICEBrowser, only exposes exception handling to versions of IE that support it, and drops the overrideMimeType call which shouldn't be necessary, anyway.

    And check if the request is created or give an alert and terminate the script
    Hopefully production code would do something more sensible than that.

    Then checking if the information is recieved from the server yet or else give a "Loading..." message
    Code:
    	http_request.onreadystatechange = function() {
    		var e = document.getElementById(id)
    		if (http_request.readyState == 4 && http_request.status == 200)	{
    			e.innerHTML = http_request.responseText
    		}
    		else	e.innerHTML = "Loading..."
    	};
    What if the transaction is completed, yet the server doesn't respond with a 200 (OK) status code?

    By the way, it's rather odd that you included a call earlier to the overrideMimeType method to force parsing as XML, yet then demonstrate the use of a textual response.

    You need to send data using http_request.send(mydata) with POST, and leave it as null when sending data with GET
    And when sending POST data, one should also send a Content-Type request header stating what form that data takes.

    Quote Originally Posted by jscheuer1 View Post
    I do have a question about:

    Code:
    http_request.overrideMimeType('text/xml');
    // See note below about this line
    I looked over it a few times and saw no explanation and am curious.
    See the XMLHttpRequest reference at XulPlanet.com.

    Unless it's not possible to get the server to send the correct Content-Type header, the method shouldn't be used.
    Mike

  7. #7
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,000
    Thanks
    44
    Thanked 3,198 Times in 3,160 Posts
    Blog Entries
    12

    Default

    Notwithstanding this issue about mime-type overrides (I will research that later, but it seems to me that writing code for public release, it might be prudent to include rather than exclude it), I have 'sexed up' my code using yours (mwinter's) as a guide. This is for use in a lightbox 'clone' I've been working on (working title 'mybox') that will not rely on external libraries and should be much leaner code wise, while supporting use of on-page content that degrades well for non-javascript enabled browsers, as well as, optionally, Ajax fetched content and an iframe method that will be Flash friendly (presented here as its part in the mybox object):

    Code:
    makeRequest:function(url) {
    mybox.box.style.backgroundColor='';
    mybox.close.className='close';
    mybox.close.style.width='';
    var http_request = false;
    if (window.XMLHttpRequest&&(!window.ActiveXObject||/http/.test(window.location.href))) { // Mozilla, Safari, IE 7 live . . .
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
    http_request.overrideMimeType('text/xml');
    }
    else if ((typeof createRequest == 'object') || (typeof createRequest == 'function'))
    http_request = createRequest();
    } else if (window.ActiveXObject) { // IE (v7 locally)
    /*@cc_on @*/
    /*@if(@_jscript_version >= 5)
    try {
    http_request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try {
    http_request = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {
    http_request = null;
    }
    }
    @end @*/
    }
    if (!http_request) {
    alert('Error creating XMLHttpRequest()');
    return false;
    }
    http_request.onreadystatechange = function() {
    if (http_request.readyState == 4 && (http_request.status == 200||!/http/.test(window.location.href))) {
    mybox.kid1.innerHTML = http_request.responseText;
    }
    else
    mybox.kid1.innerHTML = "Loading...";
    mybox.olay.style.height=Math.max(mybox.iecompattest().offsetHeight, mybox.iecompattest().scrollHeight)+'px';
    mybox.olay.style.width=Math.max(mybox.iecompattest().offsetWidth, mybox.iecompattest().scrollWidth)-(mybox.ie6wa? mybox.ie6wa() : 0)+'px';
    mybox.boxLoc(mybox.box);
    };
    http_request.open('GET', url, true);
    http_request.send(null);
    },
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  8. #8
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1 View Post
    Notwithstanding this issue about mime-type overrides (I will research that later, but it seems to me that writing code for public release, it might be prudent to include rather than exclude it), ...
    I would prefer to explain the situation properly and let the author investigate what happens in their case. After all, overriding the media type isn't really a fix, but rather a stop-gap measure that may not help in all cases: when the method isn't supported.

    No special software is necessary for checking this type of server behaviour: AJAX itself will do.

    Code:
    var httpRequest = getRequestObject();
    
    if (httpRequest) {
        httpRequest.open('GET', uri, false);
        httpRequest.send(null);
        alert(httpRequest.getResponseHeader('Content-Type'));
    }
    If no Content-Type header is sent, the getResponseHeader method will return null, otherwise the value as a string.

    Code:
    http_request.onreadystatechange = function() {
        /* ... */
    };
    http_request.open('GET', url, true);
    The open method should be called before setting event listeners. See the reference I posted previously.

    The overall pattern for using AJAX objects should be:

    1. Create object instance.
    2. Call open method.
    3. Further configure the request: add listeners, request headers, etc.
    4. Call send method.
    Mike

  9. #9
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,000
    Thanks
    44
    Thanked 3,198 Times in 3,160 Posts
    Blog Entries
    12

    Default

    OK, I'm trying to get this about as right as I can while still keeping the code down. From what you (mwinter) write, it appears (and testing seemed to bear this out), I would need to create a separate request object and send it just in order to see if the mime type is as expected and that it would then be too late to change the mime type for that request. I would be glad to be wrong about this. However, since we don't really need to worry about overrideMimeType() being available because we are testing for its existence before we invoke it, I see no problem with just going ahead and using it. I did take to heart what you said about it making no sense to override to text/xml if text/html is what is wanted though. I had been getting some errors in FF that could only be eliminated by using self closing tags on the requested page. By changing the override to text/html, these errors went away.

    Also, I had missed the first time through how you were saying that having an alert and returning false in the case where the request object couldn't be constructed didn't make too much sense in actual use. Since my code is in response to a "return get this.href" sort of onclick event, I have now chosen to return true if the request cannot be constructed. This will result in the link firing normally, loading the page if it is there and giving the server's error page for the event if the page is unavailable. If all goes well, I now return false, so that, since we now have the page as content on the 'top' page, the link will not fire.

    Finally, I tried to adhere to the order in which you recommended things be carried out/invoked. Here's the new set up:

    Code:
    makeRequest:function(url) {
    mybox.box.style.backgroundColor='';
    mybox.close.className='close';
    mybox.close.style.width='';
    var http_request = null;
    if (window.XMLHttpRequest&&(!window.ActiveXObject||/http/.test(window.location.href))) { // Mozilla, Safari, IE 7 live . . .
    http_request = new XMLHttpRequest();
    }
    else if ((typeof createRequest == 'object') || (typeof createRequest == 'function'))
    http_request = createRequest();
    else if (window.ActiveXObject) { // IE (v7 locally)
    /*@cc_on @*/
    /*@if(@_jscript_version >= 5)
    try {
    http_request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try {
    http_request = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {
    http_request = null;
    }
    }
    @end @*/
    }
    if (!http_request)
    return true;
    http_request.open('GET', url, true);
    if (http_request.overrideMimeType)
    http_request.overrideMimeType('text/html');
    http_request.onreadystatechange = function() {
    if (http_request.readyState == 4 && (http_request.status == 200||!/http/.test(window.location.href)))
    mybox.kid1.innerHTML = http_request.responseText;
    else
    mybox.kid1.innerHTML = "Loading...";
    mybox.olay.style.height=Math.max(mybox.iecompattest().offsetHeight, mybox.iecompattest().scrollHeight)+'px';
    mybox.olay.style.width=Math.max(mybox.iecompattest().offsetWidth, mybox.iecompattest().scrollWidth)-(mybox.ie6wa? mybox.ie6wa() : 0)+'px';
    mybox.boxLoc(mybox.box);
    };
    http_request.send(null);
    return false;
    },
    I'm still not clear on what the alternatives for testing only for a 200 response would be and what their implications for branching might afford, especially at that juncture in the code. However, it seems to me that if the page is missing at that point, having:

    Loading . . .

    just sit there until dismissed by the user (they can do that in my script), might not be so bad.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #10
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,000
    Thanks
    44
    Thanked 3,198 Times in 3,160 Posts
    Blog Entries
    12

    Default

    Ah, the light suddenly went on! We don't need to create a separate request to test if the mime type is as expected and to change it if possible, we can do:

    Code:
    http_request.onreadystatechange = function() {
    mybox.kid1.innerHTML = "Loading...";
    if (http_request.readyState == 4 && (http_request.status == 200||!/http/.test(window.location.href)))
    mybox.kid1.innerHTML = http_request.responseText;
    else if (http_request.overrideMimeType && http_request.readyState == 2 && http_request.getResponseHeader && http_request.getResponseHeader('Content-Type')!='text/html')
    http_request.overrideMimeType('text/html');
    mybox.olay.style.height=Math.max(mybox.iecompattest().offsetHeight, mybox.iecompattest().scrollHeight)+'px';
    mybox.olay.style.width=Math.max(mybox.iecompattest().offsetWidth, mybox.iecompattest().scrollWidth)-(mybox.ie6wa? mybox.ie6wa() : 0)+'px';
    mybox.boxLoc(mybox.box);
    };
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Tags for this Thread

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
  •