Jump to content

Some Ajax Questions


kensbeijing

Recommended Posts

I'v been reading through the Ajax tutorial on the W3schools website, and there are a few things I don't understandon this page http://w3schools.com/ajax/ajax_server.aspIt has this in part of the JS

 xmlHttp.onreadystatechange=function()	{	if(xmlHttp.readyState==4)	  {	  document.myForm.time.value=xmlHttp.responseText;	  }	}  xmlHttp.open("GET","time.asp",true);  xmlHttp.send(null);

When exactly does xmlHttp change state? Does it happen automatically?Also what does

xmlHttp.onreadystatechange=function()

mean? What's the function() that it equals to?Thanks a lot, I just need to get a few things clearer in my head.

Link to comment
Share on other sites

readystate does change automatically. Here are the values:0: AJAX.open() has not been called;1: AJAX.open() has been called but AJAX.send() has not;2: AJAX.send() has been called, but AJAX has received no response;3: AJAX is now receiving data from the server;4: AJAX has received all the data.That function you're looking at is called an anonymous function (sometimes called a lambda function). It's a function with no name created inside another function. In the AJAX object, onreadystatechange is generally assigned a callback function of some kind. It's the only way to know when the response data has arrived. In this case, the function is created internally. It is the 6 lines immediately following the word function(). Notice the curly braces, just like all functions have.Personally, I always create an external function and just assign its name to onreadystatechange. That's why the AJAX object is usually declared globally, so the callback function can look at it too. The advantage of an external function is that it makes the code more modular, portable and easy to maintain. You can copy/paste things into a new script with less rewriting, and if this script needs to play with AJAX in multiple ways (check the time, fetch an ad, create a table, etc), you don't need to create the whole process multiple times, you only need multiple callback functions. The idea looks like this:

function postData (data, callback) {	 // statements	 xmlHttp.onreadystatechange = callback;	 xmlHttp.open("POST", "whatever.asp", true); 	 xmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")	 xmlHttp.send (data); } function some_func () {	 if (xmlHttp.readyState==4) {		 // DO SOMETHING	 } }document.getElementById("foo_button").onclick = function () {	postData ("foo=bar", some_func); }

Link to comment
Share on other sites

function postData (data, callback) {	 // statements	 xmlHttp.onreadystatechange = callback;	 xmlHttp.open("POST", "whatever.asp", true); 	 xmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")	 xmlHttp.send (data); } function some_func () {	 if (xmlHttp.readyState==4) {		 // DO SOMETHING	 } }document.getElementById("foo_button").onclick = function () {	postData ("foo=bar", some_func); }

Thanks for that, now a few things:what does "xmlHttp.send (data);" do? Does it get "data" and send it to "whatever.asp"?also in "xmlHttp.onreadystatechange = callback;" could you give me an example of what "callback" would be?

Link to comment
Share on other sites

what does "xmlHttp.send (data);" do? Does it get "data" and send it to "whatever.asp"?
Yes. It sends the data, but only the data that you pass it. Data is YOUR variable. It's declared in the first argument of the postData function.
also in "xmlHttp.onreadystatechange = callback;" could you give me an example of what "callback" would be?
I did. Look at the button.onclick handler at the bottom of the code block. It calls the postData function and passes it some data (just a simple string for the sake of illustration) and a reference to the callback function (some_func). When control moves to postData, the name of the callback function is passed into the argument variable callback.
Link to comment
Share on other sites

function postData (data, callback) {	 // statements	 xmlHttp.onreadystatechange = callback;	 xmlHttp.open("POST", "whatever.php", true); 	 xmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")	 xmlHttp.send (data); } function some_func () {	 if (xmlHttp.readyState==4) {		 // DO SOMETHING	 } }document.getElementById("foo_button").onclick = function () {	postData ("foo=bar", some_func); }

OK, so if I was to make a button, which when pressed, it would show the time. Is this how I would do it:1. Make a button with id, "foo_button".2. In whatever.php I would write a function to get the time.3. In function some_func() I would write the script to display the time?

Link to comment
Share on other sites

Ok I'v tried it but it doesn't work, please tell me where Im going wrong:Ajax code

<script type="text/javascript">var AJAX;function postAJAX (data, callback) {AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null;AJAX.onreadystatechange = callback;AJAX.open ("post", "change_screen.php", asynch);AJAX.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");AJAX.send (data);}function some_func () {	 if (AJAX.readyState==4) {		 document.getElementById("result").value=AJAX.responseText;	 }}</script>

HTML

<input type="text" id="result"><a href="#" id="phonebutton" class="icon1" onclick="postAJAX(1, some_func);" title="home"></a>

change_screen.php

<?php$screen = $_POST['data'];switch($screen) {	case 1:	$response = "The identity of stevie is stevie";	break;	case 2:	$response = "This is number 2";	}echo $response;?>

Link to comment
Share on other sites

There's a syntax error in the Javascript code. You should really be using something like Firebug to help you find errors, it will tell you the exact line number. You can also be using a text editor with syntax highlighting to help you can catch things like missing quotes.

Link to comment
Share on other sites

There's a syntax error in the Javascript code. You should really be using something like Firebug to help you find errors, it will tell you the exact line number. You can also be using a text editor with syntax highlighting to help you can catch things like missing quotes.
All I did was put together a load of code, I'v just fixed some errors in it, but I have no idea how its supposed to work. Did I get the php right? I'm not sure how to respond the $response and put it into the text box.
Link to comment
Share on other sites

Yeah, the PHP is fine. Anything the PHP script outputs will be sent as the response to the AJAX object, so the AJAX object can get the response and do whatever you want with it. Since you're just sending text it can just write it out somewhere, or for more complex things you can use JSON to send an entire array or object structure back to the Javascript.

Link to comment
Share on other sites

You're getting there. Looks like a couple things went wrong:

AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null;

That's supposed to be all one line--no break after the word "new." (Copy and paste can sometimes be your enemy.)

AJAX.open ("post", "change_screen.php", asynch);

Here, you have no value for asynch. I'm thinking you mingled different pieces of my code together? Normally the value passed in that position is false. You could hard-code that and life would be good 99.99% of the time. When you have a variable in that position, pass a Boolean from the calling function. Something like:

postData (some_data, some_func, false);

Of course, your postData declaration will need the variable asynch in its parentheses.Now, your actual function call looks like this:

onclick="postAJAX(1, some_func);"

Not going to work the way you expect. If you plan to find your data in the $_POST array, you must pass a string formatted for CGI parsing, like this:

onclick="postAJAX('number=1', some_func);"

In other words, "key1=value1&key2=value2&key3=value3" and so on. You don't HAVE to pass data that way, but it's the most convenient, because PHP does the parsing for you.When you do fetch the data in PHP, the key you're looking for is the one you assigned in the data string (not the word "data," which in your set-up never gets passed to PHP at all). In other words, your script will access the data like this:

$screen = $_POST['number'];

My choice of the key "number" is entirely arbitrary. You can call it anything you want.justsomeguy is correct, however. Most of what I just explained you could gather using Firefox's built-in error console. On the PHP side, you could try var_dump($_POST) and seeing what turns up in your "result" element. If it's not what you expect, look at the javascript again and figure out why.EDIT> Corrected double-quotes

Link to comment
Share on other sites

Actually I figured it out but I need some help:

function init () {var keys = document.getElementById("button");for (var keys = button) {keys.onclick = function () {var icon = keys.class;var scrn = "screen="var screen = scrn+icon;postAJAX(screen, some_func);}}}window.onload = init;

<a name="button" id="button" class="icon1" title="1"></a><a name="button" id="button" class="icon2" title="2"></a><a name="button" id="button" class="icon3" title="3"></a><a name="button" id="button" class="icon4" title="4"></a>

It doesn't seem to do anything, I'm trying to pass on "screen=icon1" for example when I press the first link and so on. What am I doing wrong here? I'm getting one error which I don't understand "missing ; after for-loop initializer and its pointing at the end of "for (var keys = button)". I put in a semicolon but I still get the same error.

Link to comment
Share on other sites

:) Sorry about the nested double-quotes. My bad.There are several problems with your function.1. Because every element should have a unique id (or no id) getElementById() returns one element only, not a collection you can loop through. getElementByName is I believe part of HTML 5, and the latest Firefox 3 supports it (maybe just in beta?), but it's not consistently supported, and in any case, only form input elements are allowed to have names.2. You CAN use getElementByTagName(), and then filter out elements that don't match some criteria. Even easier if all the elements are contained by the same parent. Then you can do like this: var keys = document.getElementById("my_parent_node").getElementsByTagName("a"); (You supply the actual id of the parent element.)3. This will not work at all: for (var keys = button). First, button is an id that you're passing around as a string, it is not a variable. Second, you've already defined keys (in the previous statement) so the var keyword here throws an error. Third, redefining keys would erase the data you assigned to it the previous statement. Fourth, a for loop doesn't look like this. Try starting the function like this:
var keys = document.getElementById("my_parent_node").getElementsByTagName("a");var len = keys.length;for (var i = 0; i < len; i++) {   keys[i].onclick = blah blah blah . . .

Link to comment
Share on other sites

Pretty much the same way. Easiest if you use <button> tags instead of <input type="button">, because then searching by tagName will pick up what you want without grabbing every other <input> on your page.

Link to comment
Share on other sites

It was your idea to use a for loop--I'm just showing you how to do it right. Each time the loop comes around, keys refers to icon 1, then icon2, etc. The loop stops looping when i reaches the length of the keys array.Fortunately, your instinct was right. A for loop in this situation is the normal thing. The loop makes it so you don't have to get a unique reference to each element. Hard-coding references takes time, and has to be re-done any time you decide to change your ids, or if you add a new element. That may not seem like a big deal with only 4 elements to tinker with, but when you have to access 20-30 elements, you'll be glad you got into the habit now.

Link to comment
Share on other sites

I DID IT!The reason I was failing was because I was just copying and pasting examples without knowing what they meant. So now, after a thorough inevstigation of how JS works, I written a nice short version that works, without arrays. Thanks for your help, this is easy after all, its so similar to PHP.

Link to comment
Share on other sites

The AJAX object is created after a button gets pushed. So AJAX.readystate==0 will return false.What do you mean by default page? "Page" means a separate document, but I don't think that's what you mean. Do you mean default content in inputData? Just hard-code it there, and it will get overwritten when the first AJAX call happens.or do you mean something else?

Link to comment
Share on other sites

The AJAX object is created after a button gets pushed. So AJAX.readystate==0 will return false.What do you mean by default page? "Page" means a separate document, but I don't think that's what you mean. Do you mean default content in inputData? Just hard-code it there, and it will get overwritten when the first AJAX call happens.or do you mean something else?
Yea that's what I meant, I didn't think of that, thanks.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...