js doesnt work in Chrome but works in IE [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have JS code which works on IE browser.
But it doesn't work in Chrome and Mozilla.
What should be changed to make it work on these browsers?
<html>
<head>
<script type="text/javascript">
function readFile(url) {
pageRequest = new XMLHttpRequest()
pageRequest.open("GET", url, false);
pageRequest.send(null);
return pageRequest.responseText;
}
</script>
</head>
<body>
<script type="text/javascript">
var txt = readFile("?GameID=5&from=0&num=50000");
document.write(txt);
</script>
</body>
</html>
function readFile(url) {
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send();
return request;
}
var request = readFile("http://? GameID=5&from=0&num=50000");
request.onload = function() {
document.write(request.responseText);
};
this code doesnt work neither in IE nor in Chrome))
any other ideas?

This occurs because of Cross-Origin Resource Sharing, click here for more details. You need to set the Access-Control-Allow-Origin header on server and define the domains that have permissions to access the resource. I tested your code in a server with Internet Explorer and got the same error.

You're having async problems. If the HTTP request didn't finish yet, you won't be able to access request.responseText. This might work in some browsers because of pure chance. So we have to attach an onload event listener.
Try this code:
function readFile(url) {
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send();
return request;
}
var request = readFile("http://example.com/displayScore.php?GameID=5&from=0&num=50000");
request.onload = function() {
document.write(request.responseText);
};
You could also pass readFile a second parameter that is a function like this instead of returning the whole object:
function readFile(url, onload) {
//load code goes here...
if (typeof onload == "function") {
request.onload = function(){
onload(request),
};
}
}
readFile("url", function(e){
document.write(e.responseText);
});

Related

JavaScript: How to "refresh" data from same URL?

Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.

Is a get request possible with javascript?

I was wondering if it was possible to make a GET request with javascript, so it can update text without refreshing the page.
If this is possible, how can I make a get request with javascript & get the result/decode it from json?
I tried this from a past question:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", false);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
}
And, it completely stops the main thread, making the website unresponsive. What is wrong?
Currently you set the async parameter to false, so the request is sent to the server and the browser waits for the response. To make an async request, just pass true as thrid param to open
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
in addition to that, you have to register an callback, which waits for the response (and maybe to handle errors..)
xmlHttp.onload = function (e) {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
console.log(xmlHttp.responseText);
} else {
console.error(xmlHttp.statusText);
}
}
};
xmlHttp.onerror = function (e) {
console.error(xmlHttp.statusText);
};
In addition to that a note from the mozilla docs
Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 /
SeaMonkey 2.27), synchronous requests on the main thread have been
deprecated due to the negative effects to the user experience.
var isAjax=false;
function updateButton(){
if(!isAjax) { //Stops the user making a million requests per minute
isAjax=true;
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
isAjax=false;
}
}
OR jQuery...
$("#btnUpdate").click(function(){
$.get("http://xxxx.com/getSpecialSale.php", function(data, status){
$("#dicebutton").html(data);
});
});
If you want to use async you will need some code modifications, ie the stuff that happens after the response completes needs to be in a callback function as follows:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.onload = function () {
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
};
xmlHttp.send(null);
}

AJAX : What is the equivalent function of beforeSend function in XMLHttpRequest

In $.ajax there is beforeSend function, but now I'm trying to use XMLHttpRequest, I'm looking for equivalent function of beforeSend in $.ajax. How can i implement it in here.
Here is my xhr code,
xhr = new XMLHttpRequest();
var url = '../ajax/ajax_edit/update_ajax_staffUser.php';
if(file.files.length !== 0){
if(!check(fileUpload.type)){
alert("This file format not accepted");
return false;
}
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
xhr.send(fileUpload);
}else{
xhr.open('post', url+param, true);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.send(fileUpload);
}
xhr.onreadystatechange = function(e){
if(xhr.readyState===4){
if(xhr.status==200){
$('.bounce_dim').show();
setTimeout(function(){
$('.trigger_danger_alert_changable_success').show().delay(5000).fadeOut();
$('#palitan_ng_text_success').html('User successfully modified');
$('#frm_edit_staffUser')[0].reset();
$('#modal_staff').modal('hide');
$('.bounce_dim').hide();
},1000);
getUserStaffTable();
}
}
}
Since the users are uploading image to my web, I need to make a waiting interface before fires the call since the image size are too large.
You can do this by just putting the beforeSend() function before your XHR intantiation, like this:
beforeSend();
xhr = new XMLHttpRequest();
But you should define your beforeSend() function before the code above:
var beforeSend = function(){
// your code here
}
.beforeSend just calls the function before running .send, so just put your code before the line:
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.setRequestHeader('X-File-Name', fileUpload.name);
xhr.setRequestHeader('X-File-Size', fileUpload.size);
xhr.setRequestHeader('X-File-Type', fileUpload.type);
beforeSend(); // Put any code to run before sending here
xhr.send(fileUpload);

WebWorker - Ajax call - error [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 7 years ago.
I am trying to make an AJAX call to ajax.htm file. using web-worker. If it works fine, the data must keep populating at the given interval.
I dont get an error, and the get message seems to be working, but the data is not being populated on page. The message posted by the worker.js is not being listened to in the main page. Here is the code.
My webWorker.html file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Worker Sample</title>
<script type="text/javascript">
var worker = new Worker('worker.js');
// console.log(worker);
document.addEventListener("DOMContentLoaded",function(){
var result = document.querySelector('#result');
// console.log(result);
worker.addEventListener('message', function (event) {
console.log(event.data);
createElement('li', result,'',JSON.parse(event.data));
});
worker.addEventListener('error', function(err){
console.log("There was a problem",err);
});
worker.postMessage('start');
});
function createElement(elementType, parent, className, innerHTML, custom) {
var element = document.createElement(elementType);
if (parent) parent.appendChild(element);
if (className) element.className = className;
if (innerHTML) element.innerHTML = innerHTML;
if (typeof custom !== 'undefined') {
for (var prop in custom) {
element.setAttribute(prop, custom[prop]);
}
}
return element;
}
</script>
</head>
<body>
<div>
<ul id="result">Result</ul>
</div>
</body>
<html>
my worker.js is as follows:
/**
* Created by lakshmi on 7/22/15.
*/
self.addEventListener('message', function (e) {
if(e.data === 'start'){
setInterval(function () {
getData()
}, 1000);
}
function getData() {
var xhr = new XMLHttpRequest();
xhr.open('GET','ajaxcontent.htm');
xhr.withCredentials = true;
// xhr.setRequestHeader("Content-Type", "text/event-stream");
xhr.addEventListener('readyStateChange',function(){
if(xhr.readyState === 4){
self.postMessage(xhr.responseText);
}
});
xhr.send();
}
});
ajaxcontent.htm
content from external page
CORS error means, that you are doing request to other domain, and other domain did not allow cross domain request.Try to do request to your domain.Other domain can allow some headers or some request method types (POST,DELETE,GET,PUT), can allow access from all domains or from some domains.
If you are disagree with my answer, explain why.

Append array element to FormData doesn't work in Firefox 15

I'm making crossdomain ajax post request.
There is the client function:
function getUsersData()
{
var ids = ["user1_id", "user2_id"];
var fd = new FormData();
$.each(ids, function() {
fd.append('identities', this);
});
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://some-domain.com/Home/GetUsersData', true);
xhr.withCredentials = true;
xhr.onreadystatechange = responseHandler; //function is defined and not shown here
xhr.send(fd);
}
Everything works fine in Opera and Google Chrome browsers.
But Firefox says NS_ERROR_CANNOT_CONVERT_DATA: Component returned failure code: 0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA) [nsIDOMFormData.append] at the line fd.append('identities', this);
What it can be and how to fix this error?
Try to use unique keys. Something like: fd.append('identity-'+this.id, this);

Categories

Resources