Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 775
qwertynl Avatar asked Dec 18 '13 16:12

qwertynl


People also ask

Is AJAX request secure?

Ajax is not inherently secure or insecure. It does however open up 'opportunities' for insecure code.

Is it good to use AJAX?

Ajax should be used anywhere in a web application where small amounts of information could be saved or retrieved from the server without posting back the entire pages. A good example of this is data validation on save actions.

Is AJAX better than other client side technology?

AJAX can change data without reloading the web page. In other words, it implements partial server requests. The main difference among the three is that JavaScript is client-side, i.e., in the browser scripting language, whereas jQuery is a library (or framework) built with JavaScript.


1 Answers

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.

like image 187
qwertynl Avatar answered Sep 28 '22 05:09

qwertynl