By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,850 Members | 1,026 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Ajax Example

iam_clint
Expert 100+
P: 1,208
AJAX Basic Example
Expand|Select|Wrap|Line Numbers
  1. <script>
  2. //set the variables.
  3. function getArticle(id) {
  4.     var link = "/getNews.asp";
  5.     xmlhttpPost(link, id);
  6. }
  7.  
  8. //Make the actual connection.
  9. function xmlhttpPost(strURL, id) {
  10.     var xmlHttpReq = false;
  11.     var self = this;
  12.     // Mozilla/Safari
  13.     if (window.XMLHttpRequest) {
  14.         self.xmlHttpReq = new XMLHttpRequest();
  15.     }
  16.     // IE
  17.     else if (window.ActiveXObject) {
  18.         self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  19.     }
  20.     self.xmlHttpReq.open('POST', strURL, true);
  21.     self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  22.     self.xmlHttpReq.onreadystatechange = function() {
  23.         if (self.xmlHttpReq.readyState == 4) { //ready state 4 means its complete.
  24.             updatepage(self.xmlHttpReq.responseText);
  25.         }
  26.     }
  27.     self.xmlHttpReq.send(getquerystring(id));
  28. }
  29.  
  30. //set the query string to be sent
  31. function getquerystring(id) {
  32.     qstr = 'data=' + escape(id);  // NOTE: no '?' before querystring
  33.     return qstr;
  34. }
  35.  
  36. //put the data on the page.
  37. function updatepage(str) {
  38.     document.getElementById("data").innerHTML = str;
  39. }
  40. </script>
  41. <select onchange="getArticle(this.value);">
  42. <option value="1">Train hits car</option>
  43. <option value="2">Airplane Crashes</option>
  44. <option value="3">Mental Health</option>
  45. </select>
  46. <div id="data"></div>
  47.  

Now for the getNews.asp --- not fully functional code but an example
Expand|Select|Wrap|Line Numbers
  1. <%
  2. news_id = request("id")
  3. strSQL = "select * from news where news_id = " & new_id
  4. rs.open strSQL, connection, 1, 1
  5. if not rs.eof then
  6. response.write rs("story")
  7. end if
  8. %>
  9.  
Jun 21 '07 #1
Share this Article
Share on Google+
20 Comments


P: 5
Mind saying what the code dose?
Jun 24 '07 #2

iam_clint
Expert 100+
P: 1,208
it does an ajax query.
Jun 25 '07 #3

acoder
Expert Mod 15k+
P: 16,027
Mind saying what the code dose?
It gets the news articles from a database by selecting from a drop down without having to refresh/reload the page.

If you don't know Ajax is, maybe you should check out some tutorials.
Jun 25 '07 #4

P: 5
Sorry for my noobness. I looked at some AJAX tutorials and this makes a lot more sense but a few things I still don't get...
Jun 29 '07 #5

acoder
Expert Mod 15k+
P: 16,027
Sorry for my noobness. I looked at some AJAX tutorials and this makes a lot more sense but a few things I still don't get...
Like ?
Jun 29 '07 #6

P: 5
Eh, I just needa study the code more...
Jul 1 '07 #7

P: 5
Expand|Select|Wrap|Line Numbers
  1. ajax=function(strURL,sSend){
  2.     var xmlHttpReq=false
  3.     var self=this
  4.     if (window.XMLHttpRequest)self.xmlHttpReq=new XMLHttpRequest()
  5.     else if(window.ActiveXObject)self.xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP")
  6.     self.xmlHttpReq.open('POST',strURL,false)
  7.     self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  8.     self.xmlHttpReq.onreadystatechange=function(){
  9.         if (self.xmlHttpReq.readyState==4){
  10.             ajax.resul=self.xmlHttpReq
  11.         }
  12.     }
  13.     self.xmlHttpReq.send(sSend)
  14. }
  15.  
Hello i have made a little change on the main function, so you can use it like this:
Expand|Select|Wrap|Line Numbers
  1. function getArticle(id){
  2.   ajax('dataExample.php',id) // php,asp,...
  3.   alert(ajax.resul.responseText)
  4. }
  5.  
Not a big deal but now you can use the data loaded directly with the javascript, and no need to load the data into a div continer, i hope it can be helpfull
Oct 31 '07 #8

P: 5
Sorry o forgot to tell that i couldn't make it work with Firefox, it works only with ie, if some one find a way.. please :)
Oct 31 '07 #9

acoder
Expert Mod 15k+
P: 16,027
Sorry o forgot to tell that i couldn't make it work with Firefox, it works only with ie, if some one find a way.. please :)
ajax.resul.responseText is only available after the readyState is 4, so the call must be made within the anonymous function onreadystatechange or a function within that anon. function.
Oct 31 '07 #10

eragon
100+
P: 431
could somebody make a firefox compatable versoin? i officially threw out internet explorer. completely. gone. so sad. more secure. Yay Firefox!!!!!
Nov 3 '07 #11

iam_clint
Expert 100+
P: 1,208
i'm pretty sure my example works in firefox.
Nov 4 '07 #12

gits
Expert Mod 5K+
P: 5,235
ok ... let's fix the adapted code ... and a note: the original posted code in the article worked! ... but in case anybody wanted to use the adaptation we have to fix it the following way (for example):

first we adapt the ajax-function so that we may pass a callback to it, that may work with the request-response the correct way:

Expand|Select|Wrap|Line Numbers
  1. var ajax = function(strURL, sSend, cb) {
  2.     var xmlHttpReq = false;
  3.     var self       = this;
  4.  
  5.     if (window.XMLHttpRequest) {
  6.         self.xmlHttpReq = new XMLHttpRequest;
  7.     } else if (window.ActiveXObject) {
  8.         try {
  9.             xmlHttpReq = new ActiveXObject('Msxml2.XMLHTTP');
  10.         } catch (ex) {
  11.             try {
  12.                 xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
  13.             } catch (ex) {
  14.             }
  15.         }
  16.     }
  17.  
  18.     self.xmlHttpReq.open('POST', strURL, false);
  19.     self.xmlHttpReq.setRequestHeader('Content-Type', 
  20.             'application/x-www-form-urlencoded');
  21.  
  22.     self.xmlHttpReq.onreadystatechange = function(cb) {
  23.         if (self.xmlHttpReq.readyState == 4) {
  24.             cb(self.xmlHttpReq);
  25.         }
  26.     }
  27.  
  28.     // sSend is the id passed by getArticle later on ...
  29.     // build a query-string in case you need to use it
  30.     // i didn't do anything with it here
  31.     self.xmlHttpReq.send(sSend)
  32. }
  33.  
later on the call should look like this:

Expand|Select|Wrap|Line Numbers
  1. function getArticle(id) {
  2.     var cb = function(res) {
  3.         alert(res.responseText);
  4.     };
  5.  
  6.     ajax('dataExample.php', id, cb);
  7. }
kind regards

ps: and one more note to posters: please try to write the code in articles-sections a way more readable, use indentations, the var keywords etc. and use the semicolon to end your statements ... please! When adapting code then try not to post 'unready' code except you mark it as to be so.
Nov 4 '07 #13

acoder
Expert Mod 15k+
P: 16,027
i'm pretty sure my example works in firefox.
Yes it does, but I think eragon was probably referring to cheogt's adapted code.
Nov 5 '07 #14

acoder
Expert Mod 15k+
P: 16,027
could somebody make a firefox compatable versoin? i officially threw out internet explorer. completely. gone. so sad. more secure. Yay Firefox!!!!!
As pointed out, the original version in the first post does work in Firefox.

Even though you might hate Internet Explorer, it is still the most popular browser. You have no choice, but to support it (unless its a personal application which only you will use or all users will be using Firefox).

To help you, check out A Guide to Coding Cross-Browser Scripts and Browser Bugs, Quirks and Inconsistencies.
Nov 5 '07 #15

eragon
100+
P: 431
forgive me im not at all ajax savvy. i will learn.
Nov 7 '07 #16

acoder
Expert Mod 15k+
P: 16,027
This is only an example. Also check out some of the tutorials in this thread.
Nov 7 '07 #17

P: 5
Sorry for my first version, wasn't helpfull...
Final version, this one works on linux and windows, IE and FireFox

Expand|Select|Wrap|Line Numbers
  1. ajax = function(strURL, sSend) {
  2.     var xmlHttpReq=false;
  3.  
  4.     if (!window.ActiveXObject) ajax.req = new XMLHttpRequest();
  5.     else ajax.req = new ActiveXObject("Microsoft.XMLHTTP");
  6.  
  7.     ajax.req.open('POST',strURL,false);
  8.     ajax.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  9.  
  10.     ajax.req.send(sSend);
  11.     return ajax.req;
  12. }
as simple as this but works, one can request string values like:
file *.php in the server:
.....// SQL results to string ->
.....echo "[['1','a Name','a LastName','an e-mail',["XY1F",234.23,1,56]]]"
file *.html in the local browser:
.....o=ajax('data.php',usr.id)
.....aData=eval(o.responseText)
there you have an array loaded with ajax from a Data Base

The diference is that this way we dont need to use a <div> tag to load the result, in the case of loading a sub-webpage one can use:
.....document.getElementById('anyDiv').innerHTML=o .responseText
but the usr will have to w8 a bit more
Nov 15 '07 #18

gits
Expert Mod 5K+
P: 5,235
the ajax-request is async ... when returning the request object you don't have the response already ... at least not in all cases? ... so this isn't working reliable?
Nov 15 '07 #19

P: 5
@gits
The ajax is not always async, you can configure it, the example i gave does it online, no async, so you can load data from a data base and the browser waits(freeze?) until it get the answer.

I check the login in my systems like this, and more, it works good!
try it
Aug 24 '09 #20

gits
Expert Mod 5K+
P: 5,235
i see, i just overlooked the 3rd parameter in your open-method ... the XMLHttpRequest's open() method could use its 3rd parameter to set the request to sync mode ... then no callback is handled since no notification is sent for the request's readystate ... the browser freezes and waits for the response. so the browser basicly behaves as it does with a traditional page-reload - so it is much preferable to use the request-object async. even though you could use it sync and your example works.
Aug 24 '09 #21