Problem with JavaScript Worker - worker doesn't do anything - javascript

I have a Worker in Javascript
The problem is, it doesn't work :)
Here is my Worker code:
*myWorker.js*
self.addEventListener('message', function(url) {
console.log('worker starts work');
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
self.postMessage(xmlHttp.responseText);
});
main.js
function aFunction(){
var worker = new Worker('myWorker.js');
worker.addEventListener('message', function(e) {
console.log('worker has done his work');
// doing some things after worker finish work
});
worker.postMessage(url);
}
I should mention that both main.js and the myWorker.js are placed in the same folder
The worker doesn't do any part of the code
Any mistakes?
I am not that fluent in JS

as #Kaiido said:
"What you receive in the message event handler is a MessageEvent, not a string. You want to extract that data from its .data property."
the correct code is:
self.addEventListener('message', function(url) {
console.log('worker starts work');
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url.data, false);
xmlHttp.send();
self.postMessage(xmlHttp.responseText);
});

Related

JavaScript workers seems not running in background

I have this JavaScript worker for fetching data on the PHP backend.
ajax-worker.js
self.onmessage = function(e){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
postMessage(xhttp.responseText);
}
};
xhttp.open("GET", e.data, true);
xhttp.send();
}
and initiate a worker by
let worker = new window.Worker('http://localhost:8100/ajax-worker.js');
worker.postMessage('http://localhost:8100/Audit/get_total_confirmed');
worker.onmessage = function(e){
var e = JSON.parse(e.data);
document.querySelector('#stat_confirmed_listings').innerHTML = e.msg;
}
Everything is working except if I browse other pages in my website, it takes very long time to load and sometimes it returns "unreachable page" error and not until the worker completes the request or restart the server, the page then will load. What might be wrong?
Below is the view of my console console -> sources:

How should I create two object to do two different ajax calls?

I have:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText; // Update
}
};
xhr.open('GET', 'data/data-one.html', true); // Prepare the request
xhr.send(null);
Now I want to do the same thing for another link, so when the link is clicked, in the code above, data-one.html is inserted to the HTML container with an id of content in my html page.
Now lets image I have another link in my nav and want to do the same process for another html container with an id of content1 this time to insert data-two.html .
Do I have to create the httprequest in this file or another ajax file? Are the variables gonna be different?
I already tried with the same variable both in the same file and other files but I get an error saying the I can't set the innerHTML to Null. I can't find out why. Please help.
This code is just to get you started. It is very verbose and can be improved to reused. For the sake of clarity I decided to keep it simple though.
function reqListener1 () {
console.log("listener1 -- html echo", this.responseText);
}
function reqListener2 () {
console.log("listener2 -- json echo", this.responseText);
}
document.addEventListener("DOMContentLoaded", function () {
var url1 = "/echo/html/";
var url2 = "/echo/json/";
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener1);
oReq.open("GET", url1);
oReq.send();
// you could use the same variable. but you'll need to instantiate a different object
var oReq2 = new XMLHttpRequest();
oReq2.addEventListener("load", reqListener2);
oReq2.open("GET", url2);
oReq2.send();
});
Demo: http://jsfiddle.net/pottersky/7dz8r19d/1/

I need the equivalent of .load() to JS

I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.
I need to do this without jQuery:
$(document).ready(function(){
$('#a').click(function(){
$('body').append('<div id="b"></div>')
$('#b').load('x.html')
});
});
Thanks!
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
The simple answer is you're doing things that are fairly complicated to get done correctly without a library like jQuery. Here's something that "works", but with no error checking or cross-browser perfection. You really probably don't want this... but here it is.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('a').addEventListener('click', function (e) {
e.preventDefault();
var div = document.createElement('div');
div.id = 'b';
document.body.appendChild(div);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
div.innerHTML = this.response;
};
xhr.open('GET', 'x.html', true);
xhr.send();
}, false);
}, false);
</script>
</head>
<body>
<a id="a" href="#">load</a>
</body>
</html>
If you want to do it without JS, I think this will help you, add this inside #b
<iframe src="x.html"></iframe>
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
This will load "x.html" and put it inside the element.
<object type="text/html" data="my.html">
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
/* If you wanted post too */
// xmlhttp.open("POST", "/posturl", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value");
xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.alert(xmlhttp.responseText);
}
}
I found that jquery load run scripts from loaded file, which setting innerHTML to something doesn't do the trick... don't test if you can call an init() function afterwards...

javascript dynamic data loading progress bar

JavaScript dynamic data loading progress bar
i tried some of the codes found here but i am not able to get result
var req = new XMLHttpRequest();
req.addEventListener("progress", onUpdateProgress);
req.addEventListener("load", onTransferComplete);
req.addEventListener("error", onTransferFailed);
req.addEventListener("abort", onTransferFailed);
req.open("GET", "http://stackoverflow.com/questions/3790471/xmlhttprequest-js-image-loading");
req.send();
function onUpdateProgress(e) {
var percent_complete = e.loaded/e.total;
console.log(percent_complete);
}
function onTransferFailed(e) {
alert("Something went wrong. Please try again.");
}
function onTransferComplete(e) {
//Problem
}
i should get the percent load in console, but i am not able to get it
Try this
req.addEventListener("progress", onUpdateProgress, false);
and/or
req.open("GET", "http://stackoverflow.com/questions/3790471/xmlhttprequest-js-image-loading", false);

Read page XML using Javascript

Hey guys, this is driving me absolutely insane so I wanted to ask the experts on this site to see if you know how to do it =)
I'm trying to create some javascript code that can read out elements of a web page (eg. what does the first paragraph say?). Here's what I have so far, but it doesnt work and I cant figure out why:
<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
alert("done loading");
var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
alert(responseDoc.evaluate("//title",responseDoc,null,
XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}
else {
document.write("<error>could not load page</error>");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->
The alert that keeps appearing is "null" and I can't figure out why. Any ideas?
This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/
Update:
Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
//alert("done loading");
//alert(req.responseText);
var responseDoc = new DOMParser();
var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
try{
alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}catch(e){
alert("error");
}
}
else {
document.write("could not load page");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);
I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.

Categories