24

I do not seem to be able to use jQuery in my webworker, I know there must be a way to do it with XMLHttpRequest, but it seems like that might not be a good option when I read this answer.

Community
  • 1
  • 1
qwertynl
  • 3,912
  • 1
  • 21
  • 43

3 Answers3

32

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.

Community
  • 1
  • 1
qwertynl
  • 3,912
  • 1
  • 21
  • 43
  • 2
    To send JSON objects you'll need to do something along the lines of req.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); data_string = JSON.stringify(data); – Nathan Champion Feb 21 '19 at 22:10
2

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

rbrundritt
  • 16,570
  • 2
  • 21
  • 46
2

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>
Jem
  • 4,313
  • 2
  • 18
  • 20
lukyer
  • 7,595
  • 3
  • 37
  • 31