mozilla

Revision 101385 of Getting Started

  • Revision slug: Talk:AJAX/Getting_Started
  • Revision title: Getting Started
  • Revision id: 101385
  • Created:
  • Creator: Nickolay
  • Is current revision? No
  • Comment reorganize, the page has gotten quite messy

Revision Content

If you have questions related to AJAX, I suggest you try the dev-ajax mailing list. Thanks! -- dria 06:42, 21 June 2006 (PDT)

Untitled 1

Just a few notes to make on this...

I am new to this whole AJAX thing, so forgive me if i am pointing out something obvious.

1) When we are calling the open method of the http_request instance (http_request.open()) why are we specifing 'POST' as the HTTP method as the first parameter? Shouldn't it be 'GET' if we are to pass it a URL with a querystring? (as shown in the article)

2) Also, I am confused as to exactly how the server response is to send data back? Will the requested page on the server do processing depending on the data in the querystring it is passed, and then return this data? If so, how is the data passed back? Or does the whole content of a page (eg HTML) get sent back for the JS function to process?

An example of a called page sitting on the server in which the http_request object function is calling would have been useful.

Thanks

Tryst


Hi Tryst,

Re 1) When you POST, you are again sending data from the browser to the server. This data is again formatted as a query string (e.g. "name=value&foo=bar"), only it's not visible in the browser. Well in the case of an XMLHTTPRequest the GETs are also not displayed in the browser, but that was just to clarify.

In any event if you want to post, you'll do:

http_request.open('POST', 'http://example.org/somepage.php', true); http_request.send('name=value&foo=bar');


If you want to GET: http_request.open('GET', 'http://example.org/somepage.php?name=value&foo=bar', true); http_request.send(null);

Re 2)

The server can return HTML or XML that your client-side javascript will handle. It's up to you. If you look at the step 3 in the article, you'll see a way to handle an HTML file returned by the server (http://www.w3clubs.com/mozdev/test.html). Step 4) shows how to handle an XML file returned by the server - http://www.w3clubs.com/mozdev/test.xml

Hope this helps, Stoyan


Untitled 2

This code works great in Firefox and Mozilla but IE doesn't seem to want to recognize that thhe XML doc has any children. I've been searching in vain for a solution to get this to work in IE but to no avail. Does anyone know where I might be able to find something on this?

Thanks, Brian


This would fail if multiple ajax requests are being processed at the same time, wouldn't it be better to do somthing like:

<script type="text/javascript" language="javascript">


    function makeRequest(url) {

        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('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { 
           alertContents(httpRequest); 
        };
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
</script>

That way the request isn't stored in a global variable. I haven't tested this code btw, but it seems reasonable to me.


It actually works (in my case).

http_request.onreadystatechange = function() { alertContents(httpRequest); }; 

(works fine)

http_request.onreadystatechange = alertContents(httpRequest);

(does not work at all (I only received the state 0 or 1))

http_request.onreadystatechange = alertContents; 

(works but the variable is global)

What is strange is that the tutorial shows the method 2 but the actual file contains example 3 It should be updated

Pierre


I have a way to get around the single http_request resource and multiple requests to it. It still uses it as a global variable, but as an array. In a nutshell, it goes through the array and finds an available resource. If there isn't one, it creates a new one.

<script type="text/javascript" language="javascript">

var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

function xhrRequest(type) {
	if (!type) {
		type = 'html';
	}

	// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
	// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
	// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
	var xhrsend = xi.length; 
	
	// GO THROUGH AVAILABLE xi VALUES
	for (var i=0; i<xi.length; i++) {

		// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
		if (xi[i] == 1) {
			xi[i] = 0;
			xhrsend = i;
			break;
		}
	}

	// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
	xi[xhrsend] = 0;

	// SET UP THE REQUEST
	if (window.ActiveXObject) {
		try {
			xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	} else if (window.XMLHttpRequest) {
		xhr[xhrsend] = new XMLHttpRequest();
		if (xhr[xhrsend].overrideMimeType) {
			xhr[xhrsend].overrideMimeType('text/' + type);
		}
	}
	return (xhrsend);
}

function fcn(url, reqType) {

	var xhri = xhrRequest('html');			
	xhr[xhri].open('GET', url, true);
	xhr[xhri].onreadystatechange = function() {
		if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
			alert(xhr[xhri].responseText);
			xi[xhri] = 1;
			xhr[xhri] = null;
		}
	};
	xhr[xhri].send(null);
}

function loadMulti() {
	// CALL A FUNCTION THAT USES xmlHttp MULTIPLE TIMES
	fcn('file1.html');
	fcn('file2.html');
	fcn('file3.html');
}

window.onload = loadMulti();


</script>

I'm rewriting some of this from the functions I've been testing, so something might break, but the general idea's there.

Here's a sample of it in use: http://www.digitalbonsai.com/xhrmulti.php

- Luis (lu@digitalbonsai.com)

Untitled 3

Wiki newbie here - are we supposed to add to the top or to the bottom of this page?

also an ajax newbie and luddite - was hoping to be able to walk through the tutorial, on my win98 pc w/o a webserver, but it seems (now that I'm trying it) that I can't do this?

It might be nice if the "getting started" page got started by:
1) giving prerequisites - "you need to be running a webserver" seems to be one of them?
2) saying, up front, what you _can't_ do - can't get a page from a different domain?? (which was exactly what I was hoping to do)
and 3) perhaps the example could start with the complete text of the (sample) webpage, rather than just the javascript snippet; for all I know, I'm screwing up somewhere completely different since I don't know WTF I am doing. (using firefox, Refresh btn doesn't work on my test page, and http_request.status (when I can get it) is 0 )

yours in complete and utter cluelessness
Anna


Very good points you make mrs Wiki newbie. But I think that the person who wrote the article assumes that anybody interested in his article knows about all the prerequisites.

But by trial and error you found out that a client/server environment is a prerequisite and that crossdomain requests are obstructed because of security reasons (obstructed, not impossible) and your last point would be difficult, because seeing the extreme diversity of possibilities using any combination of the techniques that compile to the name AJAX would reach beyond the scope of this article.

But it would be nice to mention to developers that an xmlhttprequest() doesn't require a response, making it beautiful for counting statistics, submitting forms or other data asynchronisely while the unbothered visitor is browsing your site... <(but is that really so.....?)

Pimpy.T

Untitled 4

Hi !!

I am trying to execute the example given in this site, while clicking the "Make a Request" link... it is showing a alert saying that "There was a problem with the request".

Can any one help in this regard

Thanks & Regards, Dilip Kumar

Revision Source

<div class="note">If you have questions related to AJAX, I suggest you try the <a class="external" href="https://lists.mozilla.org/listinfo/dev-ajax">dev-ajax mailing list</a>.  Thanks! -- <a href="User:Dria">dria</a> 06:42, 21 June 2006 (PDT)</div>
<h2 name="Untitled_1"> Untitled 1 </h2>
<p>Just a few notes to make on this...
</p><p>I am new to this whole AJAX thing, so forgive me if i am pointing out something obvious.
</p><p>1) When we are calling the open method of the http_request instance (http_request.open()) why are we specifing 'POST' as the HTTP method as the first parameter? Shouldn't it be 'GET' if we are to pass it a URL with a querystring? (as shown in the article)
</p><p>2) Also, I am confused as to exactly how the server response is to send data back? Will the requested page on the server do processing depending on the data in the querystring it is passed, and then return this data? If so, how is the data passed back? Or does the whole content of a page (eg HTML) get sent back for the JS function to process?
</p><p>An example of a called page sitting on the server in which the http_request object function is calling would have been useful.
</p><p>Thanks
</p><p>Tryst
</p>
<hr>
<p>Hi Tryst,
</p><p>Re 1)
When you POST, you are again sending data from the browser to the server. This data is again formatted as a query string (e.g. "name=value&amp;foo=bar"), only it's not visible in the browser. Well in the case of an XMLHTTPRequest the GETs are also not displayed in the browser, but that was just to clarify.
</p><p>In any event if you want to post, you'll do:
</p><p>http_request.open('POST', 'http://example.org/somepage.php', true);
http_request.send('name=value&amp;foo=bar');
</p><p><br>
If you want to GET:
http_request.open('GET', 'http://example.org/somepage.php?name=value&amp;foo=bar', true);
http_request.send(null);
</p><p>Re 2)
</p><p>The server can return HTML or XML that your client-side javascript will handle. It's up to you. If you look at the step 3 in the article, you'll see a way to handle an HTML file returned by the server (http://www.w3clubs.com/mozdev/test.html). Step 4) shows how to handle an XML file returned by the server - http://www.w3clubs.com/mozdev/test.xml
</p><p>Hope this helps,
Stoyan
</p><p><br>
</p>
<h2 name="Untitled_2"> Untitled 2 </h2>
<p>This code works great in Firefox and Mozilla but IE doesn't seem to want to recognize that thhe XML doc has any children.  I've been searching in vain for a solution to get this to work in IE but to no avail.  Does anyone know where I might be able to find something on this?
</p><p>Thanks,
Brian
</p>
<hr>
<p>This would fail if multiple ajax requests are being processed at the same time, wouldn't it be better to do somthing like:
</p>
<pre>&lt;script type="text/javascript" language="javascript"&gt;


    function makeRequest(url) {

        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('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { 
           alertContents(httpRequest); 
        };
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
&lt;/script&gt;
</pre>
<p>That way the request isn't stored in a global variable. I haven't tested this code btw, but it seems reasonable to me.
</p>
<hr>
<p>It actually works (in my case). 
</p>
<pre>http_request.onreadystatechange = function() { alertContents(httpRequest); }; 
</pre>
<p>(works fine)
</p>
<pre>http_request.onreadystatechange = alertContents(httpRequest);
</pre>
<p>(does not work at all (I only received the state 0 or 1))
</p>
<pre>http_request.onreadystatechange = alertContents; 
</pre>
<p>(works but the variable is global)
</p><p>What is strange is that the tutorial shows the method 2 but the actual file contains example 3
It should be updated
</p><p>Pierre
</p>
<hr>
<p>I have a way to get around the single http_request resource and multiple requests to it.  It still uses it as a global variable, but as an array.  In a nutshell, it goes through the array and finds an available resource.  If there isn't one, it creates a new one.
</p>
<pre>&lt;script type="text/javascript" language="javascript"&gt;

var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

function xhrRequest(type) {
	if (!type) {
		type = 'html';
	}

	// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
	// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
	// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
	var xhrsend = xi.length; 
	
	// GO THROUGH AVAILABLE xi VALUES
	for (var i=0; i&lt;xi.length; i++) {

		// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
		if (xi[i] == 1) {
			xi[i] = 0;
			xhrsend = i;
			break;
		}
	}

	// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
	xi[xhrsend] = 0;

	// SET UP THE REQUEST
	if (window.ActiveXObject) {
		try {
			xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	} else if (window.XMLHttpRequest) {
		xhr[xhrsend] = new XMLHttpRequest();
		if (xhr[xhrsend].overrideMimeType) {
			xhr[xhrsend].overrideMimeType('text/' + type);
		}
	}
	return (xhrsend);
}

function fcn(url, reqType) {

	var xhri = xhrRequest('html');			
	xhr[xhri].open('GET', url, true);
	xhr[xhri].onreadystatechange = function() {
		if (xhr[xhri].readyState == 4 &amp;&amp; xhr[xhri].status == 200) {
			alert(xhr[xhri].responseText);
			xi[xhri] = 1;
			xhr[xhri] = null;
		}
	};
	xhr[xhri].send(null);
}

function loadMulti() {
	// CALL A FUNCTION THAT USES xmlHttp MULTIPLE TIMES
	fcn('file1.html');
	fcn('file2.html');
	fcn('file3.html');
}

window.onload = loadMulti();


&lt;/script&gt;
</pre>
<p>I'm rewriting some of this from the functions I've been testing, so something might break, but the general idea's there.
</p><p>Here's a sample of it in use:  http://www.digitalbonsai.com/xhrmulti.php
</p><p>- Luis (lu@digitalbonsai.com)
</p>
<h2 name="Untitled_3"> Untitled 3 </h2>
<p>Wiki newbie here - are we supposed to add to the top or to the bottom of this page?
</p><p>also an ajax newbie and luddite - was hoping to be able to walk through the tutorial, on my win98 pc w/o a webserver, but it seems (now that I'm trying it) that I can't do this?
</p><p>It might be nice if the "getting started" page got started by: <br> 1) giving prerequisites - "you need to be running a webserver" seems to be one of them? 
<br> 2) saying, up front, what you _can't_ do - can't get a page from a different domain??  (which was exactly what I was hoping to do)
<br> and 3) perhaps the example could start with the complete text of the (sample) webpage, rather than just the javascript snippet; for all I know, I'm screwing up somewhere completely different since I don't know WTF I am doing. (using firefox, Refresh btn doesn't work on my test page, and http_request.status (when I can get it) is 0 )
</p><p>yours in complete and utter cluelessness
<br> Anna
</p>
<hr>
<p>Very good points you make mrs Wiki newbie. But I think that the person who wrote the article assumes that anybody interested in his article knows about all the prerequisites. 
</p><p>But by trial and error you found out that a client/server environment is a prerequisite and that crossdomain requests are obstructed because of security reasons (obstructed, not impossible) and your last point would be difficult, because seeing the extreme diversity of possibilities using any combination of the techniques that compile to the name AJAX would reach beyond the scope of this article. 
</p><p>But it would be nice to mention to developers that an xmlhttprequest() doesn't require a response, making it beautiful for counting statistics, submitting forms or other data asynchronisely while the unbothered visitor is browsing your site...  &lt;(but is that really so.....?) 
</p><p>Pimpy.T
</p>
<h2 name="Untitled_4"> Untitled 4 </h2>
<p>Hi !!
</p><p>I am trying to execute the example given in this site, while clicking the "Make a Request" link... it is showing a alert saying that "There was a problem with the request".
</p><p>Can any one help in this regard
</p><p>Thanks &amp; Regards, Dilip Kumar
</p>
Revert to this revision