Alternative Ways To Write XHR Synchronous Behavior


I recently heard we are not suppose to using Synchronous behavior when using XHR. In my case I need Synchronous behavior. What is the best way to rewrite my calls to my services Synchronously instead of how I am doing it now. No jquery please ..

var xhReq = new XMLHttpRequest(); xhReq.open("POST", "ClientService.svc/REST/TestHtmlSend", false); xhReq.send(null); var serverResponse = JSON.parse(xhReq.responseText); return serverResponse;


You never <em>need</em> "synchronous behavior"; instead, you (the developer) just have to wrap your head around JavaScript's asynchronous nature – specifically, how to use anonymous callbacks and deal with closures.

For example, if you're doing this:

function doSomething(arg) { var number = arg + 10; // for example var data = getDetail(); data = JSON.parse(data); element.innerHTML = number + ': ' + data.name; } function getDetail() { var xhReq = new XMLHttpRequest(); xhReq.open("POST", "ClientService.svc/REST/GetDetail", false); // bad! xhReq.send(null); return xhReq.responseText; }

It could be written asynchronously:

function doSomething(arg) { var number = arg + 10; getDetail(function(data) { data = JSON.parse(data); element.innerHTML = number + ': ' + data.name; }); } function getDetail(cb) { var xhReq = new XMLHttpRequest(); xhReq.open("POST", "ClientService.svc/REST/GetDetail", true); xhReq.onreadystatechange = function() { if (xhReq.readyState == 4) cb(xhReq.responseText); } xhReq.send(null); }

Notice in the asynchronous example that your inner callback function (which executes only after the network request has completed) still has access to the outer function's number variable. This is because JavaScript has <em>static scope</em> – in other words, when you declare a function, that function will permanently have access to the variables of any functions that enclose that function.


Usually it looks like this:

var xhReq = new XMLHttpRequest(); xhrReq.onreadystatechange = function() { if (this.readyState != 4) return; if (this.status != 200) ...process error... var serverResponse = JSON.parse(xhReq.responseText); ... process the response ... } xhReq.open("POST", "ClientService.svc/REST/TestHtmlSend", true); xhReq.send(null);


  • How can I find why system can not run my application?
  • ServerSocket accept continues to block
  • Network request doesn't work when uploading a file
  • how can i render html file in node.js
  • How to augment module in project scope?
  • JavaFX/SWT WebView synchronous loadcontent()
  • In metro, what's the difference between FolderInformation and StorageFolder
  • Retrieve file size from web server
  • Elixir GenServer parallel handle_call
  • jqgrid error when deleting row
  • Loading Json as variable into jsTree
  • Sending HTML Form Multiple box via POST request with AJAX?
  • Problem in Loading xml from specified url using javascript in FF & Google Chrome
  • Play WS (2.2.1): post/put large request
  • how to adjust image in a panel in Java swing?
  • Using variable in a value field in jMeter
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Master page gives error
  • Encrypt data by using a public key in c# and decrypt data by using a private key in php
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Different response to non-authenticated users and AJAX calls
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • Updating server-side rendering client-side
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • How to pass list parameters for each object using Spring MVC?
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • How to stop GridView from loading again when I press back button?
  • LevelDB C iterator
  • Bitwise OR returns boolean when one of operands is nil
  • Is it possible to post an object from jquery to bottle.py?
  • Can't mass-assign protected attributes when import data from csv file
  • sending mail using smtp is too slow
  • Django query for large number of relationships
  • costura.fody for a dll that references another dll
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?