innerHTML works in IE and Firefox, but not Chrome - javascript

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.

Related

Jquery plugin doesn't work when loading with AJAX?

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);
}

XMLHttpRequest sends url as response text, Firefox doesn't redirect

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

setInterval runs continuously in Firefox on Android

I have a short snippet of Javascript which I want to poll a server every couple of seconds and update the DOM.
function updateCard() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
window.setInterval(updateCard,2000);
On most browsers that's what happens. There are a few one-off calls to updateCard, but on the whole the server shows ~1/2 connection per second per client.
However, when I access the page in Firefox on Android (49.0) the browser starts continuously polling /curr_card/, tens of times a second.
I've seen people suggest replacing the setInterval line with window.setInterval(function() {updateCard();},2000);, this doesn't help.
I'm pretty new to Javascript and AJAX, so have no idea why this is happening. Is it a bug in FF? I can post more code if requested.
Thanks in advance.
After testing and discussing in OP's comments, we concluded this must be an issue specific to Firefox on the OP's HTC M7, as it could not be reproduced on the same version Firefox on a Galaxy S7.
That may happen not only with Firefox on some device.
It may happen when response has not finished because of servers late answer but it sends another request and so on...
What if to do like this:
function updateCard(before, after) {
if(before) {
before();
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
if(after) {
after();
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
var updateCardRunning = false;
setInterval(function() {
if(updateCardRunning === true) {
console.log('postponing to next schedule');
return;
}
updateCard(
function() {updateCardRunning = true;},
function() {updateCardRunning = false;}
);
}, 2000);
or:
function updateCard() {
var xhttp = new XMLHttpRequest();
window.xhttp = xhttp;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
setInterval(function() {
if(window.xhttp) {
window.xhttp.abort();
}
updateCard();
}, 2000);

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...

Simple ajax not working, probably syntax error

window.onload = function(){
testAjax();
}
var testAjax = function(){
var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4){
// Server is done
try{
var p = document.getElementById['a'];
p.innerHTML = request.responseText;
//document.write(request.responseText);
}
catch(e){
document.write('More Epic Fail');
}
}
}
request.open('GET','updatethumbs.php',true);
request.send(null);
}
After a quick glance:
var p = document.getElementById['a'];
should be:
var p = document.getElementById('a');
getElementById should have ()'s, not []'s
Yup, use "rounded brackets"/parenthesis ()
There are a few names for the MSXML component and depending on what the user (in this case, you) has installed, it may not work.
EDIT: (as per question edit)
Browsers are not required to redraw the page once it's been rendered according to the CSS spec. You need to use javascript to style the items that are dynamically added in.Try, for example:
document.getElementById('a').style.border = "1px solid black";
for a simple black border.

Categories