Problems to simulate download on ie - javascript

i'm doing:
iframe = document.createElement("iframe");
frame.src="http://localhost/file.csv";
iframe.style.display='none';
document.body.appendChild(iframe);
it works fine on ff,chrome,safari but on ie always come a message about security that blocks it.
someone knows how to fix it?

If you do not want to use jQuery which is as simple as
$("result").load("file.csv"), then have a look here
http://plungjan.name/test/simpleajax.html
<html>
<head>
<title>Ajax Example</title>
<script type="text/javascript">
function xmlhttpget(URL) {
var xmlHttpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
xmlHttpReq.open('GET', URL, true);
xmlHttpReq.onreadystatechange = function() {
if (xmlHttpReq.readyState == 4) {
show(xmlHttpReq.responseText);
}
}
xmlHttpReq.send();
}
function show(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<div id="result"></div>
<input type="button" onclick="xmlhttpget('file.csv')" value="Get">
</form>
</body>
</html>

Related

Desperately trying to figure out how to display API info on HTML website [duplicate]

This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Closed 2 years ago.
Im trying to figure out a way to display crypto currency prices in real time on my website. So far Ive got a script that works at posting the current price but im having trouble using the setinterval to autorefresh the data. This is the code im using, and I think ive lost it at the setinterval part, please help!!!
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
}
setInterval(data, 3000);
</script>
</body>
</html>
I have updated your a bit please have a look it will work for you.
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
function loadBitCointPrice(){
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML = usdValue;
}
setInterval(function(){
loadBitCointPrice();
}, 3000);
</script>
</body>
</html>
You need to wrap the code that pulls the data in a function, and then use setInterval to call that function:
function pullData() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
console.log('Data updated at', new Date())
}
}
pullData() // Call it immediately the first time.
setInterval(pullData, 3000);
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
</body>
</html>

AJAX repeatitive values php for a simple to-do app

I have the following issue when adding new items. When I add a new item, multiple values are spit. I entered the first 2 in db (phpmyAdmin). The click button displays the new data without the refreshing the page. Different number of copies are returned on each click. sometimes 7 as below, sometimes 13, 30 even up to 100+ copies if the execution hangs for long. Could the onload=process() on <body> be affecting the call?
When I enter a new value, It displays multiple values. (Edit: Apologies. In the snapshot below, ["rd] is meant to spell [new])
Where could the bug be?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do List</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="js/item.js" type="text/javascript"></script>
</head>
<body onload="process()">
<div class="list">
<h1 class="header">My To Do</h1>
<div id="todo-items"></div>
</div>
<div class="list">
<div id="item-add" >
<input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off">
<button id="add">Add Item</button><br /><br />
<div id="status"></div>
</div>
</div>
</body>
item.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("cant create that object hoss");
} else {
return xmlHttp;
}
}
function fetch_data(){
$.ajax({
url:"/to-do-list/display.php",
method:"POST",
success:function(data){
$('#todo-items').html(data);
}
});
}
fetch_data();
function process() {
$(document).ready(function(){
$(document).on('click', '#add', function(){
$.ajax({
url:"/to-do-list/add.php",
method:"POST",
data:{name:name},
success:function(data){
//console.log(data + 'hi');
//$('#item-add').submit( function() {
// console.log("are you returning false?");
// return false;
//});
function clearinput (){
$('#item-add :input').each( function(){
$(this).val('');
});
}
clearinput();
fetch_data();
}
});
});
});
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
name = encodeURIComponent(document.getElementById('name').value);
xmlHttp.open("GET", "item.php?name="+name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
console.log(xmlResponse.documentElement);
message = xmlDocumentElement.firstChild.data;
// message = "colin";
document.getElementById('status').innerHTML =
'<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong!');
}
}
}
Found the bug. Took the ajax call out of the onload function in item.js

Why The News Is Not Being Pulled [XML JS Query]

Here's my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>News Site</title>
<script>
window.document.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
console.log(xmlDoc);
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br/>" + xmlDoc.getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
} else {
document.getElementById("demo").innerHTML = "Can't show it.";
}
}
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
I am a beginner in using Ajax and this is my first project. I checked with the format, even validated it with W3 Validator, and it doesn't seem to work.
Nothing is showing on the page. It's completely blank.
Can anyone point out my mistake please?
The document object does not have an onload property. Using that style of event handler assignment, you are looking for window.onload.

simple ajax nothing happens

I trying to create a small ajax script that add some text into div.
nothing happen, it's killing me.
please help.
HTML:
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body onload="process()">
OK, you made it this far
<br/>
<div id="theD">
</div>
</body>
</html>
ajax.js:
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if (window.XMLHttpRequest)(
xmlHttp = new XMLHttpRequest();
)else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return xmlHttp;
}
function process(){
alert('hi');
if (xmlHttp){
try{
xmlHttp.open("GET", "ajax.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}catch(e){
alert(e.toString());
}
}
}
function handleServerResponse(){
theD = documet.getElementById('theD');
if (xmlHttp.readyState==1){
theD.innerHTML += "Status1:server connection established <br/>";
}else if (xmlHttp.readyState==4){
if (xmlHttp.status=200){
try{
text=xmlHttp.responseText
theD.innerHTML += "Status4:request finish<br/>";
theD.innerHTML += text;
}catch(e){
alert(e.toString);
}
}else{
alert((xmlHttp.statusText);
}
}
}
the ajax.txt contain a simple string.
this is xhr2 if you want more browser support you can extend it.
http://caniuse.com/xhr2
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax</title>
<script>
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function h(){
document.getElementById('theD').innerText=this.response
}
window.onload=function(){
ajax('ajax.txt',h);
}
</script>
</head>
<body>
<div id="theD"></div>
</body>
</html>
if you have any questions about how this works or how you can extend it just ask
here you have some more info about this
https://stackoverflow.com/a/18309057/2450730
you can add ie support
by replacing
c=new XMLHttpRequest;
with
c=new XMLHttpRequest||new ActiveXObject("MSXML2.XMLHTTP.3.0");
and using onreadystatechange

javascript connect to web site code not working

Here is my javascript code which ping Google for every 10 seconds and display the connection status to html MonitorInformation element. But when I click the html file to debug, the information displayed at MonitorInformation element is always "Connecting...wait". I have debugged for some time but can not figure out. Any ideas what is wrong with my code?
Html code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Monitor.js" type="text/javascript"></script>
<title>Web Site Monitor</title>
</head>
<body onload="setup()">
<div id="MonitorInformation">Connecting...wait</div>
</body>
</html>
Java script code:
function setup() {
window.setInterval(PingWebSite, (10 * 1000));
}
function PingWebSite() {
conObj = new ActiveXObject("Msxml2.XMLHTTP");
conObj.open("GET", "http://www.google.com", true);
conObj.onreadystatechange = function() {
if (conObj.readyState === 4) {
if (conObj.status === 200) {
loading.innerText = "Service is available";
} else {
MonitorInformation.innerText = "Service is not available";
}
} else {
MonitorInformation.innerText = "Connecting to www.google.com ...";
}
}
}
EDIT 1: my fix using JSON
function setup() {
window.setInterval(PingWebSite, (10 * 1000));
}
function PingWebSite() {
var http_request = new XMLHttpRequest();
http_request.open("GET", "http://www.google.com", true);
http_request.send(null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
MonitorInformation.innerText = "Connection ok";
alert("ok");
} else {
MonitorInformation.innerText = "Connection fail";
alert("fail");
}
http_request = null;
}
};
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Monitor.js" type="text/javascript"></script>
<title>Web Site Monitor</title>
</head>
<body onload="setup()">
<div id="MonitorInformation">Connecting...wait</div>
</body>
</html>
thanks in advance,
George
You can't connect to a site outside of your URL. Unless your code is on the google.com domain it won't work.
This is a browser security item called 'Same origin policy' http://en.wikipedia.org/wiki/Same_origin_policy
If you want to do cross site calls like that you will have to use JSONP http://en.wikipedia.org/wiki/JSON as that lets you do that.
You can't cross domain XHR for which you don't have access to AFAIK.
You can do this using a hidden iFrame to get around the cross domain limitations. A quick example to get you started:
(HTML Snippet)
<body>
<div style="display: none;">
<iframe id='hiddenFrame'></iframe>
</div>
</body>
Javascript:
function setup()
{
var iFrame = document.getElementById('hiddenFrame');
var changeEvent = function ()
{
loading.innerText = "Service is Available";
}
// IE
iFrame.onload = changeEvent;
// Firefox
iFrame.onreadystatechange = changeEvent;
setInterval(PingWebSite, (10 * 1000));
}
function PingWebSite() {
var iFrame = document.getElementById('hiddenFrame');
iFrame.src = 'http://www.google.com';
}
Could it be that you forgot a semicolon there? E.g.: ...body onload="setup();"...

Categories