From BC$ MobileTV Wiki
(Redirected from InnerHTML)
Jump to: navigation, search

Asyncronous Javascript And Xml Asynchronous JavaScript and XML (commonly abbreviated AJAX) is emerging as one of the most effective methods of creating interactive Web Applications. It is a method which combines client-side script (typically JavaScript, JScript or VBscript) and server-side data or computation, along with some RIA techniques (such as DHTML, Drag & Drop and Animation) for improving the usability and interactivity of Web Applications. [1]



AJAX is based on 4 existing web standards which are well defined and supported by all major browsers:

  1. JavaScript
  2. XML
  3. HTML
  4. CSS


AJAX Client-Server


Advantages of AJAX include:

* Don't need to reload the whole page to send or get updated data
* Added interactivity and responsiveness can be acheived
* Works with ANY server-side language


Disadvantages of AJAX are:

* Doesn't work if JavaScript is disabled
* Asynchronous nature can cause data contention or race problems when updating data


Domain processing

URL parameters

[5] [6] [7] [8]



XMLHttpRequest (commonly abbreviated XHR) is a standard mechanism for creating requests to server-side components of an application (typically for passing or requesting data dynamically, in an AJAX-type call).


http_request = new XMLHttpRequest();

ActiveX Object

IE 5/6

http_request = new ActiveXObject("Microsoft.XMLHTTP");

IE 7/8

http_request = new ActiveXObject("Msxml2.XMLHTTP");

AJAX Multi-user Session



http_request.open('GET', 'data.xml');


http_request.open('POST', 'data.xml', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


http_request.open('POST', 'data.xml');
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader('X_METHODOVERRIDE', 'PUT');


http_request.open('POST', 'data.xml');
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader('X_METHODOVERRIDE', 'DELETE');

[9] [10]


Given the XHR instantiation above, you can set the request header using the following (after initializing the XMLHttpRequest object):

xhr.setRequestHeader('User-Agent', 'BC$');

You can also access the response Header as follows:


[11] [12] [13] [14] [15] [16] [17]

Response Handler

The following code handles changes in state as a result of a request (i.e. response returned, errors, redirects, etc):

//ready to read response data
if (mypostrequest.readyState==4) {
 //200 = HTTP status code for 'Successfully completed request'
 if (mypostrequest.status==200){
  document.getElementById("result").innerHTML = http_request.responseText; //simply write raw text from response, in this example
  alert("ERROR: Could not make request")


Parse HTML

Content Injection

Inner HTML

innerHTML is a DOM element for changing page elements and content dynamically, without reloading or refreshing the entire page.

[18] [19]

[20] [21] [22] [23] [24] [25]

Inner Text

Text Content


[26] [27] [28] [29]











[33] [34]


A callback is a function which is called from a reference. It is useful for delaying processing of a method.

For example, to set a time to wait before running the function:

setTimeout(callback, TIME) 

where TIME is a millisecond representation like 1000 for 1 second.

For processing results of an XML HTTP Request (XHR) when they are ready

http_request.onreadystatechange = callback 

Complete AJAX XHR callback example:

<script type="text/javascript">
function myFunction()
    loadXMLDoc("ajax_info.txt",alertResponse); //can call alertResponse or showResponse or any other new method as a "callback"
function loadXMLDoc(url,_cfunc)
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange=(typeof _cfunc != "undefined") ? _cfunc : showResponse;
function showResponse()
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
function alertResponse()
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
 < div id="myDiv">Let AJAX change this text</div >
 <button type="button" onclick="myFunction()">Change Content</button>



"A promise object represents a value that may not be available yet. The primary method for interacting with a promise is its then method."[36]

[44] [45] [46] [47] [48] [49] [50] [51] [52] [53]




[57] [58] [59] [60] [61]


WebWorkers are like AJAX requests that run completely in the background on a separate thread outside of the main render/blocking thread of the browser instance. They are useful for any AJAX-like data fetching operations that take longer to process (and could even be beneficial in areas that simply have a chance of taking longer).

See also: HTML5 WebWorkers

Service Workers

Service Workers are a technology to help Proxy (intercept) all incoming and outgoing requests, modify it, return something immediately, or decide based on a caching policy whether or not it should try to fetch a response from the server.

 if ('serviceWorker' in navigator) {
   .then(() => console.log('ServiceWorker installed'))
   .catch(err => console.log('Error: ', err));

 self.addEventListener('activate', (event) => {
       .then(function(cache) {
          return cache.addAll([
          console.log('ServiceWorker ready, assets cached');

See also: HTML5 Service Workers


Same Origin Policy

The Same Origin Policy (also known as the Same Domain Policy) dates back to the days of Netscape and limits the sending of requests, data, objects or documents through JavaScript across separate domains, protocols, or port numbers.


AJAX Proxy

Server-side Proxy


Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries.

On the server-side, it is relatively straightforward to add support for CORS, requiring only the addition of a Header to the hosting server. The following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

Header set Access-Control-Allow-Origin "*"

When sent in a request/response header, it would look like the following:

Access-Control-Allow-Origin: *


Access-Control-Allow-Origin: http://sometrustedsite.com

One limitation of this new security mechanism is the inability to represent multiple domains, as such, you must either allow all sites to pull data from your APIs or pages (as per the example above), or, only respond back that you do or don't specific single site. The only way to "whitelist" multiple domains is to handle this on the server-side, perform a lookup and list that single allowed domain, for instance in Apache Web Server you could add the required header dynamically this way:

# ------------------------------------------------------------------------------
# Allow loading JavaScript, JSON, XML or CSS files to a list of trusted partners
# ------------------------------------------------------------------------------
<FilesMatch "\.(js|json|xml|css)$">
   <IfModule mod_headers.c>
       SetEnvIf Origin "http(s)?://(www\.)?(trustedsite1.com|trustedsite1.net|trustedsite2.ca|dev.trustedsite3.tv)$" AccessControlAllowOrigin=$0
       Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

[65] [66] [67]

On the client-side, XMLHTTPRequest2 supports a new withCredentials property that is required to be set to enable a CORS request to go out to a CORS-compliant/configured server. In IE which lacks XHR2, you can instead use XDomainRequest method. For simplicity, you could use the following function[68]:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
   // Check if the XMLHttpRequest object has a "withCredentials" property, which only exists on XMLHTTPRequest2 objects
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
   // Otherwise, check for XDomainRequest, which exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
   // Otherwise, CORS is not supported by the browser.
    xhr = null;
  return xhr;

[73] [74] [75] [76] [77] [78] [79] [80] [81] [82]







Cross-Origin Embedder Policy (COEP): https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy

Reverse AJAX

AJAX works by allowing us to fetch new content or data on demand, or at a set interval, as desired. However, sometimes we want data to flow in the other direction (from origin server towards our active/running application). In these cases, we can use a "Reverse AJAX" technique to push data from remote servers into our Web Application.

To realize Reverse AJAX, there are a few alternatives:

  1. HTML5 WebSockets (persistent connections with a server and Server-Sent Events for receiving messages as push notifications that can be processed in the DOM using JavaScript)
  2. Applet sockets (a predecessor of the emerging WebSockets standard, early Applets were the first to enable real-time communication using a dedicated TCP socket connection between client and server, that was only closed when the user closed the Applet or page it was embedded in)
  3. Slow-load (also called "Long-polling", uses keep-alive Connection and lengthy server-side maximum execution times to "wait" for new incoming data)
  4. Polling (simulates a real-time push connection by periodically checking on a set interval, with a small enough interval the data arrives in near-realtime)
  5. HTTP Streaming (also called long-lived HTTP, keeps connection alive between client and server even after data is delivered, until expiration timestamp is passed)
  6. Comet (aka long-held HTTP, once client requests an endpoint, the server returns the data as slowly as possible, trying to maintain an open connection for as long as possible, using "no timeouts")
  7. Piggyback (aka "store and forward", new data arrives at the server and gets stored, the client makes an unrelated request and the Reverse AJAX data gets appended on top of the unrelated response, usually with some form of divider or header to identify where the unrelated data starts and ends)
  8. META refresh in hidden iFrame (aka poor-man's Reverse AJAX, simply refresh the page on a set interval so it can be updated, then the contents of the iFrame can be grabbed... refreshing the iFrame too often can affect server load times)

[85] [86] [87] [88] [89]








See: JavaScript





Orbited provides a pure JavaScript/HTML socket in the browser. It is a web router and firewall that allows you to integrate web applications with arbitrary back-end systems. You can implement any network protocol in the browser—without resorting to plugins.


Open Source (Free)

Open Source (Commercial)

Closed Source (Free)

Closed Source (Commercial)





[93] [94] [95]


External Links


  1. For more info check out the wikipedia page on AJAX: wikipedia:AJAX
  2. AJAX -- Introduction and Advantage: http://ajaxblog.com/archives/2009/01/25/ajax-introduction-and-advantage
  3. Why use AJAX?: http://www.interaktonline.com/support/articles/Details/AJAX:+Asynchronously+Moving+Forward-Why+use+AJAX%3F.html?id_art=36&id_asc=309
  4. Troubles with Asynchronous Ajax Requests and PHP Sessions: http://www.chipmunkninja.com/Troubles-with-Asynchronous-Ajax-Requests-g@
  5. Javascript function to get URL query string parameters: https://snipplr.com/view/13239/javascript-function-to-get-url-query-string-parameters
  6. Get URL Parameters with JavaScript: https://html-online.com/articles/get-url-parameters-javascript/
  7. How to Get URL Query Parameters with Javascript (process with for each): https://usefulangle.com/post/78/javascript-get-url-parameters
  8. How to get URL parameter using jQuery or plain JavaScript?: https://stackoverflow.com/questions/19491336/how-to-get-url-parameter-using-jquery-or-plain-javascript
  9. An absolute Guide to JavaScript Http Requests (XHR .vs. Fetch .vs. Axios lib): https://medium.com/javascript-in-plain-english/an-absolute-guide-to-javascript-http-requests-44c685edfa51
  10. Why JavaScript Developers Should Prefer Axios Over Fetch: https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c
  11. The XMLHttpRequest Object: http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/#dfn-setrequestheader
  12. Understanding User-Agent Strings: http://msdn.microsoft.com/en-us/library/ms537503(v=VS.85).aspx
  13. Accessing the web page's HTTP Headers in JavaScript: https://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript
  14. How to read/get response header from AJAX/HTTP/Service/API call or response: https://medium.com/@jsguyhenry/how-to-read-get-response-header-from-ajax-http-service-api-call-or-response-c873c5fbf9b8
  15. jQuery - get AJAX response headers: https://stackoverflow.com/questions/11440918/jquery-get-ajax-response-headers
  16. jQuery and AJAX response header: https://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header
  17. jQuery & AJAX response header: https://cmsdk.com/node-js/jquery-and-ajax-response-header.html
  18. W3Schools - InnerHTML: http://www.w3schools.com/htmldom/prop_anchor_innerhtml.asp
  19. Writing Dynamic Content with JavaScript: http://jennifermadden.com/javascript/dhtml/dynamicLayerContent.html
  20. innerHTML & DOM Methods: https://web.archive.org/web/20111218002440/http://www.dustindiaz.com/innerhtml-vs-dom-methods/
  21. Why innerHTML can ruin your AJAX applications http://blog.systemcoder.com/2006/12/why-innerhtml-can-ruin-your-ajax.html
  22. The Problem With innerHTML http://www.julienlecomte.net/blog/2007/12/38/
  23. The innerHTML dilemma: http://domscripting.com/blog/display/35
  24. BetterInnerHTML - an alternative to innerHTML: http://www.optimalworks.net/resources/betterinnerhtml/
  25. An ultimate alternative solution to innerHTML: http://www.optimalworks.net/blog/2007/web-development/javascript/innerhtml-alternative
  26. JavaScript append: https://www.javascripttutorial.net/javascript-dom/javascript-append/
  27. innerHTML vs appendChild() - Which approach is better?: https://marian-caikovski.medium.com/innerhtml-vs-appendchild-e74c763846df
  28. Important difference between standard HTML tables and div tables: https://medium.com/geekculture/important-difference-between-standard-html-tables-and-div-tables-b6b094ec2c79
  29. Illustration for post innerHTML vs appendChild(): https://innerhtmlvsappendchild.onrender.com
  30. innerHTML vs createElement: http://cute-solutions.blogspot.com/2006/07/innerhtml-vs-createelement.html
  31. What is faster to insert into DOM— HTML or DOM nodes?: https://medium.com/codex/what-is-faster-to-insert-into-dom-html-or-dom-nodes-ff11586f8570
  32. Modern alternatives to innerHTML and appendChild(): https://marian-caikovski.medium.com/modern-alternatives-to-innerhtml-and-appendchild-296b9e5a5d28
  33. W3schools -- Element Object - removeChild() method: https://www.w3schools.com/jsref/met_node_removechild.asp | DEMO
  34. How to clear the content of a div using JavaScript?: https://www.geeksforgeeks.org/how-to-clear-the-content-of-a-div-using-javascript/
  35. Try this Editor: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
  36. Mozilla Dev - Javascript Promises: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
  37. Promise/A+ spec on GitHub: https://github.com/promises-aplus/promises-spec/blob/1.0.0/README.md
  38. Q - the asynch JS Promise library: http://documentup.com/kriskowal/q/ SRC | DOCS | EXAMPLES
  39. Q - httpReadRetry example: https://gist.github.com/kriskowal/593052
  40. BluebirdJS: http://bluebirdjs.com/docs/getting-started.html | SRC (Promise polyfill lib)
  41. Native Promise ONLY: https://github.com/getify/native-promise-only
  42. A small embeddable Promise polyfill: https://github.com/bramstein/promis
  43. Lightweight ES6/A+ compliant Promise Polyfill: https://github.com/taylorhakes/promise-polyfill
  44. MozDev -- Promise API: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  45. JavaScript Promise API: https://davidwalsh.name/promises
  46. Aren't promises just callbacks?: https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks/22562045#22562045
  47. What is the "explicit Promise construction" antipattern and how do I avoid it?: https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it
  48. Function that retries with setTimeout: https://stackoverflow.com/questions/31922159/javascript-function-that-retries-with-settimeout
  49. Promise Retry Design Patterns: https://stackoverflow.com/questions/38213668/promise-retry-design-patterns/44577075#44577075
  50. Promises -- Repeat operation until it succeeds?: https://stackoverflow.com/questions/26694467/promises-repeat-operation-until-it-succeeds#26694802
  51. Promises and setTimeout: https://stackoverflow.com/questions/42771837/promises-and-settimeout#42774486
  52. Wrapping jQuery AJAX requests with simple Promises: https://codepen.io/aevanson/pen/mGVNaR
  53. Promises in "vanilla JS": https://medium.com/@vikingjonsson/promises-in-vanilla-js-10588e629abb
  54. Fetch API: https://davidwalsh.name/fetch
  55. Introduction to the Fetch API: https://www.sitepoint.com/introduction-to-the-fetch-api/
  56. Using Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  57. Async Await JavaScript Tutorial – How to Wait for a Function to Finish in JS: https://www.freecodecamp.org/news/async-await-javascript-tutorial/
  58. How To Use Async and Await In JavaScript: https://www.js-tutorials.com/javascript-tutorial/how-to-use-async-and-await-in-javascript/
  59. NodeJS -- Modern Asynchronous JavaScript with Async and Await: https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await
  60. How To Master Async/Await With This Real World Example: https://medium.com/free-code-camp/how-to-master-async-await-with-this-real-world-example-19107e7558ad (real-time currency converter example)
  61. Using async/await in a forEach loop (HINT: you can’t): https://blog.devgenius.io/using-async-await-in-a-foreach-loop-you-cant-c174b31999bd
  62. Beacon spec (LATEST): https://w3c.github.io/beacon/
  63. Beacon API: https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
  64. Understanding Web Security Checks in Firefox (Part 1): https://blog.mozilla.org/attack-and-defense/2020/06/10/understanding-web-security-checks-in-firefox-part-1/
  65. Access-Control-Allow-Origin M+ultiple Origin Domains?: https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains
  66. Setting CORS (cross-origin resource sharing) on Apache with correct response headers allowing everything through: https://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/
  67. Vary -- origin response header and CORS exploitation: https://security.stackexchange.com/questions/151590/vary-origin-response-header-and-cors-exploitation#151596
  68. Using CORS: http://www.html5rocks.com/en/tutorials/cors/
  69. wikipedia: Cross-origin resource sharing
  70. Browser Support Table - CORS: http://caniuse.com/cors
  71. CORS-Compliant REST API with Jersey and ContainerResponseFilter: http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/
  72. CORS-enable Tomcat - Why REST with JSONP when you can CORS?: http://sunnytalkstech.blogspot.ca/2012/01/why-rest-with-jsonp-when-you-can-cors.html (Tomcat)
  73. Cookies With My CORS: https://quickleft.com/blog/cookies-with-my-cors/
  74. Cross-site XMLHttpRequest with CORS: https://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
  75. Putting it all together – CORS tutorial for IIS: https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/
  76. Understanding CORS (in Spring): https://spring.io/understanding/CORS
  77. Understanding and using CORS (in RESTlet): http://restlet.com/company/blog/2015/12/15/understanding-and-using-cors/
  78. Making Cross-Domain Requests with CORS: https://www.eriwen.com/javascript/how-to-cors/
  79. How to use CORS to access Google APIs: https://developers.google.com/api-client-library/javascript/features/cors
  80. HTML5 - CORS: https://www.tutorialspoint.com/html5/html5_cors.htm
  81. CORS request - why are the cookies not sent?: https://stackoverflow.com/questions/8863571/cors-request-why-are-the-cookies-not-sent#8870830
  82. Basics of CORS (Cross-Origin Resource Sharing): https://dzone.com/articles/basics-of-cors
  83. Mozilla Dev docs -- Is Access-Control-Allow-Origin: * insecure?: https://advancedweb.hu/2019/11/12/cors_star/
  84. Safely reviving shared memory (with evolving W3C recommended COOP & CORE HTTP headers): https://hacks.mozilla.org/2020/07/safely-reviving-shared-memory/
  85. wikipedia: Reverse Ajax
  86. The Slow Load Technique/Reverse AJAX - Simulating Server Push in a Standard Web Browser: http://www.obviously.com/tech_tips/slow_load_technique
  87. Using Server Push (aka Reverse AJAX): http://biese.wordpress.com/2009/03/03/using-server-push-aka-reverse-ajax/
  88. Exploring Reverse AJAX: http://gmapsdotnetcontrol.blogspot.com/2006/08/exploring-reverse-ajax-ajax.html
  89. Google -- Polling Like It's the 90s: https://dzone.com/articles/google-polling-like-its-the-90s ( technical review of the live score feature in Google search results)
  90. Building an iOS photo feed with Pusher and Raspberry Pi: https://blog.pusher.com/building-ios-photo-feed-pusher-raspberry-pi/
  91. Inject a script tag with remote src and wait for it to execute: https://stackoverflow.com/questions/8578617/inject-a-script-tag-with-remote-src-and-wait-for-it-to-execute
  92. Understanding the Async JS event loop: https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff
  93. JSL (JavaScript Loader): www.andresvidal.com/jsl#jsl.load
  94. $script.js – Another JavaScript loader & dependency manager: https://web.archive.org/web/20110224163338/http://dustindiaz.com/scriptjs | SRC
  95. 用 asyncJS 异步加载 JavaScript: https://ljw.me/2013/10/20/asyncjs.html | SRC
  96. Element innerText/textContent for all browsers: http://perrymitchell.net/article/element-innertext-textcontent-for-all-browsers/
  97. 'innerText' works in IE, but not in Firefox: https://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox/1359822#1359822
  98. innerText vs innerHtml vs label vs text vs textContent vs outerText: https://stackoverflow.com/questions/24427621/innertext-vs-innerhtml-vs-label-vs-text-vs-textcontent-vs-outertext
  99. innerText vs. textContent: https://kellegous.com/j/2013/02/27/innertext-vs-textcontent/
  100. The poor, misunderstood innerText: http://perfectionkills.com/the-poor-misunderstood-innerText/
  101. What is callback hell?: https://www.quora.com/What-is-callback-hell?share=1

See Also

JavaScript | XML | JSON | jQuery | HTML5 | xHTML | HTML | DHTML | Drag & Drop | CORS | JSP | C#