I'm having some problems with this code I've done:
function server_status() {
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://mcapi.sweetcode.de/api/v2/?info&ip=jogar.millenarycraft.com', true);
xhr.onreadystatechange = new function(){
document.getElementById("server_counter").innerHTML = 'ReadyState: ' + xhr.readyState;
if (xhr.readyState == 4) {
data = JSON.parse(xhr.responseText);
if(data.status){
document.getElementById("server_counter").innerHTML = '<span>Jogadores online: <span style="color:#FD7C00;">' + data.player.online + '</span></span>';
}else{
document.getElementById("server_counter").innerHTML = '<span style="color:#FD7C00;">Servidor offline!</span>';
}
}
}
xhr.send();
}, 1000);
}
It is inside a script tag and work as well, but I'm having problems just from document.getElementById("server_counter").innerHTML = 'ReadyState: ' + xhr.readyState; on. I noticed that the readystate stops on 1 and I don't know why! Can anyone help me?
PS: And the problem is not with the url, because I did a PHP version and it worked very well. I just want to use JavaScript because I need to update the value without refreshing the page in a certain time.
I think you have an unintended error:
xhr.onreadystatechange = new function(){
Change to:
xhr.onreadystatechange = function(){
new should most certainly not be there. I think as it is your function is called once before you've called xhr.send(), hence xhr.readyState is 1.
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'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).
This script is throwing this error every half second:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. signals.js:9
req.onreadystatechange signals.js:9
update_table signals.js:26
req.onreadystatechange
This is signals.js - I want it to reload every 5 seconds and if there is new content, to trigger the "Sound" alert.
function update_table()
{
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.status == 200)
{
if(req.readyState == 4)
{
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
First check if the req.readyState equals 4 and then check if the req.status equals 200.
The HTTP status code isn't set before the request is processed, so you can't use it before the readyState equals 4.
You can check this link for more info about the onreadystatechange event.
You need to first check whether req.readyState equals to 4 (means DONE), and only then check for req.status:
function update_table() {
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
// Here: first check for readyState
if(req.readyState === 4 && req.status == 200) {
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
See XMLHttpRequest doc for details.
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
}
};
The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
Im just starting to learn JavaScript so I really don't know much about it.
You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.
So, with jquery your code
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
becomes
$(document).load(function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
$.get(url, {}, function(data) {
$('#sales').html(data);
});
});
Shorter, cleaner and works in all browsers!
I think you want to use:
request.onreadystatechange = function() {
instead of:
request.onload = function() {
And change the way you check the return value.
See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.
Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.