function getJSON(url){
return new Promise(function(resolveFN, crashFN){
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'json';
processing(); //this is for special notifcation appear
request.onload = function(e){
resolveFN(request.response);
removeProcessing(); //this is for special notifcation disappear after 'onload'
};
request.onerror = function(){
debugger; //this is not invoked when url is wrong
crashFN(new Error(' Couldn\'t load at: ' + url));
};
request.send();
});
}
next when I use eventListener - it doesn't catch an error:
var prev = document.getElementById('prev');
prev.addEventListener('click', function(){
getJSON('http://marsweather.ingenology.com/v1/archive/1').then(function(response){
debugger; //this is invoked
console.log(response);
}).catch(function(err){
debugger; // and this is not invoked. why?
console.log('errrrrrrer ', err);
});
});
What could be the reason that catch doesn't work inside the eventListener?
UPDATE: Dmitriy Loskutov suggested this - When should XMLHttpRequest's onerror handler fire
The Promise isn't at fault. You need to check appropriately for the status in your onload handler.
request.onload = function(e){
if (request.status === 200) {
resolveFN(request.response);
}
else {
rejectFN(...);
}
removeProcessing(); //this is for special notifcation disappear after 'onload'
};
Related
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);
});
I use jquery to auto scroll blog post.. They normally works fine but it doesn't scroll or work at all when I load that page via AJAX.. The problem could be how I'm calling ajax to load the page..may be callback function issue which I'm not getting right? here is the ajax code I'm using:
function loadme() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loadcontent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
xhttp.send();
}
They all work but jquery post auto scroll will not work.. Is that due to callback function? I'm not sure.. Someone suggest or correct the code... Would appreciate volunteered help
Addition
I did alternative callback function but that too doesn't work either..
<div id="loadcontent"> Content to load/replace</div>
<button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse
Blogs</button>
//ajax with callback function
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}
Since you have tagged jquery and you also mentioned jquery in your anwser,
I am providing a jquery solution.
//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
ajaxRequest("url", loadcontent);
});
// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
$.ajax({
url: url,
method: "get",
success: function (response) {
callback(response);
},
error: function (jqXHR, exception) {
// handle errors
}
});
}
// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
$("#loadcontent").html(message);
$("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}
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
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);
I am confuse about the xhr return event, as I can tell, there are not so much different between onreadystatechange --> readyState == 4 and onload, is it true?
var xhr = new XMLHttpRequest();
xhr.open("Get", url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4)
{
/* do some thing*/
}
};
xhr.send(null);
or
xhr.onload = function() { /* do something */ }
This is almost always true. One significant difference, however, is that the onreadystatechange event handler also gets triggered with readyState==4 in the cases where the onerror handler is usually triggered (typically a network connectivity issue). It gets a status of 0 in this case. I've verified this happens on the latest Chrome, Firefox and IE.
So if you are using onerror and are targeting modern browsers, you should not use onreadystatechange but should use onload instead, which seems to be guaranteed to only be called when the HTTP request has successfully completed (with a real response and status code). Otherwise you may end up getting two event handlers triggered in case of errors (which is how I empirically found out about this special case.)
Here is a link to a Plunker test program I wrote that lets you test different URLs and see the actual sequence of events and readyState values as seen by the JavaScript app in different cases. The JS code is also listed below:
var xhr;
function test(url) {
xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() { log(xhr, "readystatechange") });
xhr.addEventListener("loadstart", function(ev) { log(xhr, "loadstart", ev.loaded + " of " + ev.total) });
xhr.addEventListener("progress", function(ev) { log(xhr, "progress", ev.loaded + " of " + ev.total) });
xhr.addEventListener("abort", function() { log(xhr, "abort") });
xhr.addEventListener("error", function() { log(xhr, "error") });
xhr.addEventListener("load", function() { log(xhr, "load") });
xhr.addEventListener("timeout", function(ev) { log(xhr, "timeout", ev.loaded + " of " + ev.total) });
xhr.addEventListener("loadend", function(ev) { log(xhr, "loadend", ev.loaded + " of " + ev.total) });
xhr.open("GET", url);
xhr.send();
}
function clearLog() {
document.getElementById('log').innerHTML = '';
}
function logText(msg) {
document.getElementById('log').innerHTML += msg + "<br/>";
}
function log(xhr, evType, info) {
var evInfo = evType;
if (info)
evInfo += " - " + info ;
evInfo += " - readyState: " + xhr.readyState + ", status: " + xhr.status;
logText(evInfo);
}
function selected(radio) {
document.getElementById('url').value = radio.value;
}
function testUrl() {
clearLog();
var url = document.getElementById('url').value;
if (!url)
logText("Please select or type a URL");
else {
logText("++ Testing URL: " + url);
test(url);
}
}
function abort() {
xhr.abort();
}
It should be the same thing. onload was added in XMLHttpRequest 2 whereas onreadystatechange has been around since the original spec.
No, they are not the same. If you encounter a network error or abort the operation, onload will not be called. Actually, the closest event to readyState === 4 would be loadend.
The flow looks like this:
onreadystatechange
readyState === 4
⇓
onload / onerror / onabort
⇓
onloadend
in simple code here how they are handle the error
xhr.onload = function() {
// same or allowed cross origin
if (this.status == 200) {
}
else {} // error http status not 200
};
xhr.onerror = function() {
//error: cross origin, bad connection
};
VS
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (this.status == 200) {
}
else {} // error: cross origin, http status not 200, bad connection
}
};