I would like to seek your help about xmlhttprequest. I would like to perform xmlhttp request sending out to get pictures repeatly from server only when the previous http response is received.
In server side, I have created http responses which tagged with xmlhttp status =900.So I want to send out the request once the response due to previous request is received, otherwise, the program should wait until its arrival.
For example:
When I press the button somewhere in the browser, it triggers first picture (jpeg) request to server, then waiting the server's response. After getting the Http response with status marked as 900, xmlhttp will decode the response and display the picture on (image).
In the following code, by capturing the packet with wireshark, I think I success to get the right packet flow. However, the picture can not be shown in the DIV.
Can anyone help me ? Thanks a lot and a lot!
enter code here
function init(url)
{
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.send();
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e)
{
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64=btoa(raw);
var dataURL="data:image/jpeg;base64,"+b64;
document.getElementById("image").src = dataURL;
};
xmlHTTP.onreadystatechange=function(){
buff(xmlHTTP.status);
}
}
buff(status){
if (status=900){
sleep(1000);
init('/images/photos/badger.jpg');
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</head>
<body>
<div id="image"><h2>picture display here</h2></div>
<button type="button" onclick=buff(900)>Get Picture</button>
enter code here
There are several problems with your code.
Markup
The problem with your markup is, that you are using a div tag to display an image. The src attribute is not supported on div tags. You should use an img tag instead like this:
....
<img id="image" />
<button type="button" onclick="buff(900)">Get Picture</button>
Statuscode
Why are you using a status of 900? If the request was correct and the image was loaded, please use a status of 200.
Image loading
Why are you even using an XMLHttpRequest for loading images?
You could simply change the src attribute on the img tag and the browser will request the image.
If you want to reload the image you could just refresh the src attribute. If all images a served under the same URL, you can add a request param like the current time:
document.getElementById("image").src = "/images/photos/badger.jpg#" + new Date().getTime();
This way the browser will request the image again and won't use the one allready loaded and cached. See this answer for further info. (Actually the question is nearly the same as yours...)
Sleep function
Your sleep function will use resources because it's a loop that will constantly run for the specified time. While it runs, it will add numbers and do comparisons that are completly unnecessary.
please use something like the javascript build in setTimeout():
buff(status) {
if(status === 900) {
setTimeout(funciton(){
init('/images/photos/badger.jpg');
}, 1000);
}
}
Update: working example
I set up a working example in the code snippet. It loads images from the same url, but they are served randomly on each request by lorempixel.
I reorganized the image loading. Actually there was another problem. You startet the next image loading with onreadystatechange. This will fire for each change of the readystate and not only when the image is loaded. Therefore I start the next buff() from the onload() like so:
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var dataURL = "data:image/jpeg;base64," + b64;
document.getElementById("image").src = dataURL;
buff(this.status);
};
xmlHTTP.send();
For convenience I added a button for stopping the loading of new images.
For your example you just have to change the imageUrl and imageStatus variables.
var imageUrl = "http://lorempixel.com/400/200/", // set to "/images/photos/badger.jpg" for your example
imageStatus = 200, // set to 900 for your example
stopped = true;
function stopLoading() {
stopped = true;
}
function loadNextImage(url) {
if(!stopped) { // only load images if loading was not stopped
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var dataURL = "data:image/jpeg;base64," + b64;
document.getElementById("image").src = dataURL;
buff(this.status); // set the next timer when the current image was loaded.
};
xmlHTTP.send();
}
}
function buff(status) {
if (status === imageStatus) {
setTimeout(function() {
loadNextImage(imageUrl + "?" + new Date().getTime());
}, 1000);
} else {
// Status does not match with expected status.
// Therefore stop loading of further images
stopLoading();
}
}
function init() {
stopped = false;
loadNextImage(imageUrl);
}
document.getElementById("start").onclick = function(){
init(imageUrl);
};
document.getElementById("stop").onclick = stopLoading;
<img id="image" />
<button type="button" id="start">Get pictures</button>
<button type="button" id="stop">No more pictures</button>
Related
I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support
I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>
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 have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.
Hi all I have this code:
function test()
{
req = new XMLHttpRequest();
req.upload.addEventListener("progress", updateProgress, false);
req.addEventListener("readystatechange", updateProgress, false);
req.addEventListener("error", uploadFailed, false);
req.addEventListener("abort", uploadCanceled, false);
var data = generateRandomData(currentPayloadId);
totalSize = data.length;
req.open("POST", "www.mydomain.com/upload.aspx");
start = (new Date()).getTime();
req.send(data);
}
function updateProgress(evt)
{
if (evt.lengthComputable) {
total = totalSize = evt.total;
loaded = evt.loaded;
}
else {
total = loaded = totalSize;
}
}
Also, my server responds to the initial OPTIONS request for upload.aspx with 200 and the Access-Control-Allow-Origin: *
and then the second request POST happens
Everything seems in place and it's working great on FireFox but on G Chrome the updateProgress handler is not getting called but only once and then the lengthComputable is false.
I needed the Access-Control-Allow-Origin: * because this is a cross-domain call, the script parent is a resource on a different server then the upload.aspx domain
Anyone can give me some clues, hints, help please? is this a known issue with G Chrome?
Thank you!
Ova
I think I have a solution for your problem
I don't know what is behind this function "generateRandomData()"
var data = generateRandomData(currentPayloadId)
It is working when I change into this:
var data = new FormData();
data.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
Small explanation: You need manually to append to form data an file input form, where fileToUpload is <input type="file" name="fileToUpload" id="fileToUpload" />
And in your updateProgress function in IF part you can add something like this to track progress console.log(evt.total +" - "+ evt.loaded)
This is working in Google Chrome browser. I have tested in new browser version 57
I made for myself an upload progress form 4 years ago, which means that this code is working in old browser version too.
A whole code snippet will be looking like this
function test()
{
req = new XMLHttpRequest();
req.upload.addEventListener("progress", updateProgress, false);
req.addEventListener("readystatechange", updateProgress, false);
req.addEventListener("error", uploadFailed, false);
req.addEventListener("abort", uploadCanceled, false);
//var data = generateRandomData(currentPayloadId);
var data = new FormData();
data.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
totalSize = data.length;
req.open("POST", "www.mydomain.com/upload.aspx");
start = (new Date()).getTime();
req.send(data);
}
function updateProgress(evt)
{
if (evt.lengthComputable) {
total = totalSize = evt.total;
loaded = evt.loaded;
console.log(evt.total +" - "+ evt.loaded)
}
else {
total = loaded = totalSize;
}
}
I had this problem when the page your are loading doesn't contain a
Content-Length: 12345
in the header, where 12345 is the length of the response in bytes. Without a length parameter, the progress function has nothing to work on.
First, make sure that "www.example.com" is added to the manifest.json, like so:
manifest.json
{
..
"permissions": [
"http://www.example.com/",
"https://www.example.com/",
],
..
}
Then I think your example should work.
For more information about using xhr in google chrome extensions the docs are here.
Also the CSP docs are worth taking a look at if what I provided above does not.
This could simply be a compatibility issue with the XMLHttpRequest.upload property. It returns an XMLHttpRequestUpload object, but if you try find that object spec in MDN it doesn't exist so how do we know which browsers fully support it.
XMLHttpRequest.upload Compatability
Have you tried listening for progress directly on the xhr:
req.addEventListener("progress", updateProgress, false);
I use jQuery for progress like that:
$.ajax({
url : furl,
type : method,
data : data,
//...
},
xhr : function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$(".progress-bar").css("width", + percent + "%");
$(" .status").text(position + " / " + total + " (" + percent + "%)");
}, true);
}
return xhr;
},