Is this how everyone does AJAX?

Soldato
Joined
31 May 2006
Posts
4,239
Location
127.0.0.1
Hi all

Looking into using AJAX for a new project I'm doing and found this...

Code:
<script type="text/javascript">
var http = false;

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}

function validate(user) {
  http.abort();
  http.open("GET", "ajax2.asp?name=" + user, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>

<h1>Please choose your username:</h1>

<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id="foo"></div>
</form>

...which uses some code in ajax2.asp to determine whether a username is valid (checks for length, existing username in a database etc...). Is this how everyone else does AJAX?
 
Use jQuery's Ajax system. It'll save you huge amounts of time and is cross-browser compatible out the box. :). Infact, use it for getting/updating your form fields too.

With classic ASP and AJAX I basically do this:
Use jQuery to query an AJAX address for a particular function, let's say /scripts/ajax/product.asp and pass parameters of action as say 'get_product_information' and id of 1234 for product 1234. This script then calls a products class to get its data as a recordset array and returns it as a JSON formatted string which jQuery can process.

If you really like I can dig some code samples out later.
 
Last edited:
Validation? Use jQuery's also excellent validation plugin.

Here's some old code (it can probably be shrunk) which performs an AJAX email validation check using that plugin:

Code:
account_email: {
	required: true,
	email: true,

	// Check account is ok
	remote: {
		url: "../business/scripts/ajax/account.asp",
		type: "post",
		data: {
			action: 'account_profile_available',
			profile_id: function() {
				return $("#account_email").val();
			}
		}
	}
}
 
As said, use JQuery - you can then get rid of all those horrible inline attributes in your html ;)

Just googled 'jquery ajax username' and came up with these examples:

http://www.shawngo.com/gafyd/index.html
http://9lessons.blogspot.com/2008/12/twitter-used-jquery-plug-in.html

Sure there are loads more too :)

EDIT: these are not like pho's example, where you should have the validation plugin setup already - you can them directly.

Off topic, have used the validation plugin for ages and never knew it had build in ajax validation :)
 
Once you get into it and the syntax it uses jQuery saves hours of time. There's hundreds of decent plugins for it too which is even better :).
 
Back
Top Bottom