Is it feasible to do an AJAX request from a Web Worker? Is it feasible to do an AJAX request from a Web Worker? ajax ajax

Is it feasible to do an AJAX request from a Web Worker?


Of course you can use AJAX inside of your webworker, you just have to remember that an AJAX call is asynchronous and you will have to use callbacks.

This is the ajax function I use inside of my webworker to hit the server and do AJAX requests:

var ajax = function(url, data, callback, type) {  var data_array, data_string, idx, req, value;  if (data == null) {    data = {};  }  if (callback == null) {    callback = function() {};  }  if (type == null) {    //default to a GET request    type = 'GET';  }  data_array = [];  for (idx in data) {    value = data[idx];    data_array.push("" + idx + "=" + value);  }  data_string = data_array.join("&");  req = new XMLHttpRequest();  req.open(type, url, false);  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  req.onreadystatechange = function() {    if (req.readyState === 4 && req.status === 200) {      return callback(req.responseText);    }  };  req.send(data_string);  return req;};

Then inside your worker you can do:

ajax(url, {'send': true, 'lemons': 'sour'}, function(data) {   //do something with the data like:   self.postMessage(data);}, 'POST');

You might want to read this answer about some of the pitfalls that might happen if you have too many AJAX requests going through webworkers.


If trying to call a service on another domain that uses JSONP, you can use the importScripts function. For example:

// Helper function to make the server requests function MakeServerRequest() { importScripts("http://SomeServer.com?jsonp=HandleRequest"); } // Callback function for the JSONP result function HandleRequest(objJSON) { // Up to you what you do with the data received. In this case I pass // it back to the UI layer so that an alert can be displayed to prove // to me that the JSONP request worked. postMessage("Data returned from the server...FirstName: " + objJSON.FirstName + " LastName: " + objJSON.LastName); } // Trigger the server request for the JSONP data MakeServerRequest();

Found this great tip here: http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html


Just use JS function fetch() from Fetch API. You can also set up a lot of options like CORS bypassing and so on (so you can achieve the same behavior like with importScripts but in much cleaner way using Promises).

the code looks like this:

var _params = { "param1": value};fetch("http://localhost/Service/example.asmx/Webmethod", {    method: "POST",    headers: {        "Content-Type": "application/json; charset=utf-8"    },    body: JSON.stringify(_params )}).then(function (response) {    return response.json();}).then(function (result) {    console.log(result);});

and the web.config of the webservice looks like this:

<configuration>    <system.webServer>        <httpProtocol>            <customHeaders>                <add name="Access-Control-Allow-Origin" value="*" />                <add name="Access-Control-Allow-Headers" value="Content-Type" />            </customHeaders>        </httpProtocol>    </system.webServer></configuration>