Current location: Hot Scripts Forums » General Web Coding » JavaScript » [Community Project] AJAX library


[Community Project] AJAX library

Reply
  #1 (permalink)  
Old 05-05-08, 01:51 PM
Vicious's Avatar
Vicious Vicious is offline
Community VIP
 
Join Date: Jan 2007
Location: Belgium
Posts: 584
Thanks: 0
Thanked 0 Times in 0 Posts
[Community Project] AJAX library

Every once in a while, someone comes here, and asks some sort of AJAX implementation. There are a lot of libraries out there that do the job just fine. But there are some downsides: must of us don't use a library, or we don't use the same one; these libraries are pretty big because they do a lot of other stuff too; ...

So maybe we can create our own little AJAX implementation, which does only that. A sort of community project. Everyone who feels like they can contribute can do so.

Because every project doesn't start without some goals to be met, here's what I think should be available from functionality. This list is not definate, and I encourage everyone to bring on some new ideas, or tell why you think another idea is not good:
  • All functionality should be written either as a singleton or as a class. No collection of separate functions.
  • Completely independend of other JS libraries
  • When using the functionality, it should be as easy as it gets. Preferably with just 1 function call for the user
  • Support for both GET and POST calls
  • Pure Javascript, no PHP for the backend, because we don't need that
  • When an AJAX call is finished, a custom function should be called (specified by the user of the library)
  • Support for other events (readyState) is welcome, but maybe not necessary for a first version
  • Clean code, with lots of comments

That's already quite a list, but I'm sure you can come up with other things. We'll discuss the goals first, and then we'll start coding.
__________________
Jack Bauer makes Chuck Norris cry

Last edited by Vicious; 05-05-08 at 01:53 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #2 (permalink)  
Old 05-06-08, 12:41 AM
infinitylimit's Avatar
infinitylimit infinitylimit is offline
Code Guru
 
Join Date: Jun 2004
Location: Oregon
Posts: 758
Thanks: 0
Thanked 0 Times in 0 Posts
Logistically speaking are you thinking something that is going to have multiple releases with a development team, a website, a support team... What was your plan for the mobile for this project?

Getting something off the ground such as AJAX library requires a commit, generally only 1 committed person is need but without that you are generally looking at another for the "dream's deffered" bucket.
__________________
Hawk Enterprises -- Home to PHP games, open-source code, tutorials and free downloads
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #3 (permalink)  
Old 05-06-08, 04:54 AM
Vicious's Avatar
Vicious Vicious is offline
Community VIP
 
Join Date: Jan 2007
Location: Belgium
Posts: 584
Thanks: 0
Thanked 0 Times in 0 Posts
Nothing too difficult with a development team, site, ... and such. Just a couple of people who write parts of a first version. When it is ready, we can all review it, and make some changes. Then that would be the final version.

It has to be small and simple really. When people use it, and they notice something is really lacking, then we can update the script. I didn't have development cycles in my mind.

As for the support, people can ask questions here in the forum. But most functionality will be described in a sticky; with a FAQ if necessary.

Like you said, 1 person should be enough to write this, but I wanted to create something we can all work together. And to make sure we don't end up up in the "dreams deffered" bucket, we just do it as simple as possible.

When we see this is going well, and there are a couple of people who are contributing, then maybe we can do a second project, or something bigger. The ultimate goal is to give "newbies" who ask something that is simple for us a piece of code that we all know.
__________________
Jack Bauer makes Chuck Norris cry
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #4 (permalink)  
Old 05-07-08, 09:38 PM
End User's Avatar
End User End User is offline
Level II Curmudgeon
 
Join Date: Dec 2004
Posts: 3,027
Thanks: 14
Thanked 35 Times in 33 Posts
Quote:
Originally Posted by Vicious View Post
Nothing too difficult with a development team, site, ... and such. Just a couple of people who write parts of a first version. When it is ready, we can all review it, and make some changes.
Okay, here's what I've got so far for a framework, you guys may need to fill in a few of the other bits:

HTML Code:
<script type="text/javascript">
// add code here...

</script>
It's very lean code, weighing in at only 65 bytes so far. It lacks some functionality but it's a start.
__________________
I don't live on the edge, but sometimes I go there to visit.
-------------------------------------------------------------------------
Sanitize Your Data | Oracle Date & Substring Functions | Code Snippet Library | [url=http://www.codmb.com/Call Of Duty[/url]
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #5 (permalink)  
Old 05-08-08, 08:55 AM
Vicious's Avatar
Vicious Vicious is offline
Community VIP
 
Join Date: Jan 2007
Location: Belgium
Posts: 584
Thanks: 0
Thanked 0 Times in 0 Posts
I can't get it to work
Nah good start. I guess if no-one has anything to add/say/comment, I'll just write something then. When I have time....
__________________
Jack Bauer makes Chuck Norris cry
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #6 (permalink)  
Old 05-08-08, 09:55 AM
UnrealEd's Avatar
UnrealEd UnrealEd is offline
Community Liaison
 
Join Date: May 2005
Location: Antwerp, Belgium
Posts: 3,165
Thanks: 4
Thanked 25 Times in 25 Posts
I think it's a great idea, but I'm afraid only one or two people will be working on it, and the others will simply wait for the result and then copy it. I've written an ajax class 2 days ago (I needed it for an application I was writing, and got sick of all the codeI had to write over and over), and this is what I have so far:
Javascript Code:
  1. /**
  2. * ajax.js $Id 1.23
  3. *
  4. * This script is a wrapper for the XMLHttpRequest class available in the DOM
  5. * implementation on several browsers. Additional support is built-in for the
  6. * Microsoft MSXML.XMLHTTP activeXObjects.
  7. *
  8. * @author Thomas Devriendt
  9. */
  10.  
  11. // Holds the different ActiveXObjects that can be used for XML Http Requests
  12. var aXMLHttpActiveXObjects = new Array ('MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');
  13. // When the defaultCallbackHandler function is used the
  14. // XMLHttpRequest.responseXML is stored in here
  15. var oResponseXML = new Object ();
  16. // When the defaultCallbackHandler function is used the
  17. // XMLHttpRequest.responseText is stored in here
  18. var sResponseText = new String ();
  19.  
  20. /**
  21. * Initiates a new XMLHttpRequest
  22. */
  23. function AJAX () {
  24.     this.sRequestMethod = "POST";
  25.     this.sRequestPage = null;
  26.     this.oAjaxRequest = null;
  27.     this.aParams = new Array ();
  28.    
  29.     this.createAjaxRequestObject ();
  30. }
  31.  
  32. /**
  33. * Creates a new XMLHttpRequest object.
  34. * When no object could be created, it alerts the viewer of the page
  35. */
  36. AJAX.prototype.createAjaxRequestObject = function () {
  37.     if (window.XMLHttpRequest) {
  38.         this.oAjaxRequest = new XMLHttpRequest ();
  39.     } else if (window.ActiveXObject) {
  40.         for (var i=0; i<aXMLHttpActiveXObjects.length; i++)
  41.             try {
  42.                 this.oAjaxRequest = new ActiveXObject (aXMLHttpActiveXObjects[i]);
  43.                 break;
  44.             } catch (e) {}
  45.     } else {
  46.         alert ("Apparently this browser doesn't support AJAX");
  47.         return;
  48.     }
  49.     this.oAjaxRequest.onreadystatechange = this.defaultCallbackHandler;
  50. };
  51.  
  52. /**
  53. * Sets the callbackHandler.
  54. * The callbackHandler is the function that will process the data once
  55. * the XMLHttpRequest is completed
  56. *
  57. * @param function The callbackHandler function
  58. */
  59. AJAX.prototype.setCallbackHandler = function (callbackHandler) {
  60.     if (typeof (callbackHandler) == 'function')
  61.         this.oAjaxRequest.onreadystatechange = callbackHandler;
  62.     else
  63.         alert ("setCallbackHandler expects it's first argument to be of type function, got " + typeof (callbakcHandler));
  64. };
  65.  
  66. /**
  67. * Sets the request method of the XMLHttpRequest.
  68. * Only the values "POST" and "GET" are allowed
  69. *
  70. * @param string Either "POST" or "GET", default is "POST"
  71. */
  72. AJAX.prototype.setRequestMethod = function (requestMethod) {
  73.     if (typeof (requestMethod) == 'string') {
  74.         switch (requestMethod.toUpperCase()) {
  75.             case "POST":
  76.                 this.sRequestMethod = "POST";
  77.                 break;
  78.             case "GET":
  79.                 this.sRequestMethod = "GET";
  80.                 break;
  81.             default:
  82.                 this.sRequestMethod = "POST";
  83.         }
  84.     } else
  85.         alert ("setRequestMethod expects it's first argument to be of type string, got " + typeof (requestMethod));
  86. };
  87.  
  88. /**
  89. * Sets the page to which the request needs to be made.
  90. *
  91. * @param string The request page
  92. */
  93. AJAX.prototype.setRequestPage = function (requestPage) {
  94.     if (typeof (requestPage) == 'string')
  95.         this.sRequestPage = requestPage;
  96.     else
  97.         alert ("setRequestPage expects it's first argument to be of type string, got " + typeof (requestPage));
  98. };
  99.  
  100. /**
  101. * When additonal headers need to be send, you can use this function
  102. *
  103. * @param string The header identifier
  104. * @param string The header contents
  105. */
  106. AJAX.prototype.setRequestHeader = function (headerId, headerContent) {
  107.     if (typeof (headerId) == 'string' && typeof (headerContent) == 'string')
  108.         this.oAjaxRequest.setRequestHeader (headerId, headerContent);
  109.     else
  110.         alert ("setRequestHeader expects it's first and second argument to be of type string, got " + typeof (headerId) + " and " + typeof (headerContent));
  111. };
  112.  
  113. /**
  114. * Makes a request to the previously set request page.
  115. * It is possible to pass on parameter that need to be sent to the request
  116. * page as well.
  117. * It is also possible to pass on a different requestPage than the one that
  118. * was set earlier. This way you only need 1 AJAX object to make requests
  119. * to different pages
  120. *
  121. * @param Array An associative array containing the parameters that need
  122. *            to be sent to the request page
  123. * @param string A request page the request needs to be made to [optional]
  124. */
  125. AJAX.prototype.makeRequest = function (params, requestPage) {
  126.     if (requestPage != null)
  127.         this.setRequestPage (requestPage);
  128.    
  129.     if (this.sRequestMethod == 'GET') {
  130.         this.oAjaxRequest.open (this.sRequestMethod, this.sRequestPage + "?" + this.buildQueryString (params));
  131.         this.oAjaxRequest.send ();
  132.     } else if (this.sRequestMethod == 'POST') {
  133.         this.setRequestHeader ('content-type', 'application/x-www-form-urlencoded');
  134.         this.oAjaxRequest.open (this.sRequestMethod, this.sRequestPage);
  135.         this.oAjaxRequest.send (this.buildQueryString (this.aParams));
  136.     } else
  137.         alert ("Invalid requestMethod found; found " + this.sRequestMethod);       
  138. };
  139.  
  140. /**
  141. * Sets a param that needs to be sent to the requestPage.
  142. *
  143. * @param string The name of the parameter
  144. * @param object The value of the parameter
  145. */
  146. AJAX.prototype.setParam = function (key, value) {
  147.     this.aParams[key] = value;
  148. };
  149.  
  150. /**
  151. * Creates a query string.
  152. * A query string has the following form:
  153. *   var1=value1&var2=value2
  154. * This is the way data will be sent via the XMLHttpRequest to the request
  155. * page
  156. *
  157. * @param Array An array containing all parameters that need to be sent to
  158. *            the request page
  159. */
  160. AJAX.prototype.buildQueryString = function (params) {
  161.     var queryString = new String ();
  162.     for (var i in params)
  163.         queryString += i + "=" + escape (params[i]) + "&";
  164.     return queryString.substr (0, queryString.length-1);
  165. };
  166.  
  167. /**
  168. * The default callback handler.
  169. * This function will simply store the responseXML and responseText
  170. * in 2 global variables that can be accessed anywhere in your script
  171. */
  172. AJAX.prototype.defaultCallbackHandler = function () {
  173.     /*if (this.oAjaxRequest.readyState == 4 && this.oAjaxRequest.status == 200) {
  174.         sResponseText = this.oAjaxRequest.responseText;
  175.         oResponseXML = this.oAjaxRequest.responseXML;
  176.     }*/
  177. };
At this moment it is working except when you use the defaultCallbackHandler function to handle the onreadystatechange event. It simply throws an error saying that there's no such field 'oAjaxRequest'. It seems like it has lost the the instance of the AJAX class...

Here's how I use it:
Javascript Code:
  1. <script type="text/javascript" src="Ajax.js"></script>
  2. <script type="text/javascript">
  3. var a = new AJAX();
  4. a.setRequestMethod ("GET");
  5. a.setRequestPage ("random_test.htm");
  6. a.setCallbackHandler(test);
  7. a.makeRequest ();
  8.  
  9. function test () {
  10.     alert (a.oAjaxRequest.responseText);
  11. }
  12. </script>

I'm not yet sattisfied with the current way it is working, as you need to access the AJAX.oAjaxRequest field outside the class to get the responseText and responseXML fields during the onreadystatechange event (when you register a different callbackHandler). Maybe someone has a better idea to work around this problem...
__________________
"Good judgement comes from experience, and experience comes from bad judgement." - Fred Brooks

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #7 (permalink)  
Old 05-08-08, 10:05 AM
End User's Avatar
End User End User is offline
Level II Curmudgeon
 
Join Date: Dec 2004
Posts: 3,027
Thanks: 14
Thanked 35 Times in 33 Posts
One thing I've noticed about most AJAX handlers out there is that they typically do GET requests...often I have to pass a substantial amount of data 10K, 100K, etc) and GET may fail silently or (even worse) truncate the data when that much data is passed (depending on the browser). I've gone to using POST for most of my AJAX stuff now. The code below is a simple example of what I use....I'm posting it in the hopes that perhaps it may help someone here:

HTML Code:
<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form = document.forms['foo'];
    var word = form.word.value;
    qstr = 'w=' + escape(word); 
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}
</script>
And a sample form:

HTML Code:
<form name="foo">
  <p>word: <input name="word" type="text">  
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/somepage.php")'></p>
  <div id="result"></div>
</form>
__________________
I don't live on the edge, but sometimes I go there to visit.
-------------------------------------------------------------------------
Sanitize Your Data | Oracle Date & Substring Functions | Code Snippet Library | [url=http://www.codmb.com/Call Of Duty[/url]
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #8 (permalink)  
Old 05-08-08, 12:37 PM
Vicious's Avatar
Vicious Vicious is offline
Community VIP
 
Join Date: Jan 2007
Location: Belgium
Posts: 584
Thanks: 0
Thanked 0 Times in 0 Posts
Good start Thomas. However, I do hate the .prototype approach
It's certainly something we can base our work on, although in the end I would want to usage to be much simpler. Just a simple function call with max 2-3 parameters.
__________________
Jack Bauer makes Chuck Norris cry
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
ajax or css i dont know mjr JavaScript 2 03-02-07 12:37 PM
AJAX problem with php dynamic url scott2500uk PHP 3 10-28-06 11:33 AM
News:E-XD++ MFC Library Professional Edition V9.20 is released (100% Source Code)! jackonlyone General Advertisements 0 02-21-06 10:58 PM
need Java script ( Ajax) Calendar, tree, grid curtisannev Job Offers & Assistance 1 10-30-05 09:59 PM


All times are GMT -5. The time now is 09:10 AM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.