Posted By

jatkins on 11/27/10


Tagged

ajax XMLHttpRequest dhtml


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

brandonjp
wirenaught


Simple AJAX Library


 / Published in: JavaScript
 

Public domain. To create an AJAX object: myAJAXObject = new ajax;. To submit and/or retrieve data: myAJAXObject.sendRequest('GET', 'search_results.php', false, 'query=test&per_page=9', 'divSearchResults');. Updated 1/28/11 to fix bug preventing POST data from being sent.

  1. /*
  2.  * AJAX Library
  3.  * Created November 26, 2010
  4.  * Updated January 28, 2011
  5.  * Released into the public domain by Josh Atkins
  6.  */
  7.  
  8. function ajax() {
  9. this.ajaxObject = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
  10. var replace_html = false;
  11. this.ajaxObject.onreadystatechange = function() {
  12. if(this.readyState==4&&this.status==200) {
  13. if(replace_html) {
  14. if(document.getElementById(replace_html).value)
  15. document.getElementById(replace_html).value = this.responseText;
  16. else
  17. document.getElementById(replace_html).innerHTML = this.responseText;
  18. }
  19. }
  20. };
  21. ajax.prototype.sendRequest = function(method, uri, async, data, replace_html_element) {
  22. replace_html = replace_html_element;
  23. this.ajaxObject.open(method.toUpperCase(), uri + (method.toLowerCase() == 'get' ? '?' + data : ''), async);
  24. this.ajaxObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  25. this.ajaxObject.send(method.toLowerCase() == 'get' ? '' : data);
  26. };
  27. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: OliveiraEvandro on November 30, 2010

Hey, man, nice job! Just a little issue about calling: "myAJAXObject.send('GET', 'searchresults.php', false, 'query=test&perpage=9', 'divSearchResults');"

The method stands for 'sendRequest()' instead of 'send()'.

However, a very tiny and useful code. Gratz.

Posted By: jatkins on January 29, 2011

Thanks for pointing that out. I've fixed it now. The code is basically based off this from W3Schools, but it's more flexible and some of the code is redone in a more compact form.

You need to login to post a comment.