my scriptedHTTP.js has:
var req = new XMLHttpRequest();
req.open("GET", "scripts/text.txt", true);
req.send(null);
var div = document.createElement('div');
div.innerHTML = req.responseText;
when I load the page, browser console shows:
XHR finished loading: GET "http://localhost:8000/scripts/text.txt".
but I get nothing on the page:
how do I handle responseText so it shows on the page?
thanks.
Ajax is asynchronous. req.responseText only it works when the load is performed successfully. You must use the req.onreadystatechange that is triggered when the load status has changed, so now you can use req.responseText
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
div.innerHTML = req.responseText;
}
};
Related
I want to reload the current page with javascript if a specific url is doing a redirection.I don't need to know the redirection url.The xhr request is being performed and i do get 302 redirect when i inspect the request but my specific redirection isn't happening.
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://www.filterbypass.me/s.php?k=BbrSU%2F%2F39m5gKhLDr31ZqjKYgrAdALscySz%2B6YarDYTH5G9hSDc%2B&b=4&f=norefer');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 301 || xhr.status == 302) {
//url expired , reload
console.log('perform redirection');
window.location.replace('https://www.google.com');
}
}
};
xhr.send();
I don't see the console.log and i already tried with xhr.readyState == 2.
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','http://example.com/',true);
xmlHTTP.send();
I just keep getting XHR failed loading: GET, can anyone help???
Thanks
If the server your contacting doesn't have CORS set in the header (e.g. access-control-allow-origin: *), you will not be able to make the request. If you don't have access to the server to set a CORS header, you'll need to contact the server from a server you do control and then pass that to the browser (either with a CORS header or not if it's served from the same domain)
But your code works fine. The problem is with your http://example.com/ not returning
http://jsbin.com/zuhobidako/edit?html,js,console,output
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','https://jsonplaceholder.typicode.com',true);
xmlHTTP.send();
xmlHTTP.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.body.innerHTML =
this.responseText;
}
};
For server status errors, add this to onreadystatechange
if( this.status > 299 && this.readyState == 4) {
console.log('Server Error: ' + xmlHTTP.statusText);
}
For xmlHTTP code errors...
xmlHTTP.onerror = function() {
console.log('xmlHTTP Error', xmlHTTP.responseText)
}
I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);
Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script
There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}