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
Related
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>
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
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.
I want to load js on the fly which is happening but the one more js file which is included in index is loading before (file i am loading dynamically) is there way to fix the order
i am adding global.js dynamically and i want variable declared in global.js shoud be initialised before dynamicjs.DynamicJs is loaded
------------- Index.html -------------
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection" >
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script src="js/dyn.js"></script>
<script></script>
<script>
sap.ui.localResources("dynamicjs");
var view = sap.ui.view({id:"idDynamicJs1", viewName:"dynamicjs.DynamicJs", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
function loadScript(url){
var xhrObj = createXMLHTTPObject();
// open and send a synchronous request
xhrObj.open('GET', url, false);
xhrObj.send('');
var e = document.getElementsByTagName("script")[1];
var d = document.createElement('script');
d.src = url;
d.type = 'text/javascript';
d.async = false;
d.defer = false;
e.parentNode.insertBefore(d,e);
}
function addScriptDynamically(){
loadScript('js/global.js'+'?scheme=12345');
}
function createXMLHTTPObject(){
var xmlhttp=new XMLHttpRequest();
if( typeof xmlhttp == 'undefined' || xmlhttp == null )
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
/*call function */
addScriptDynamically();
Why won't you try to load script with jQuery.getScript()
http://api.jquery.com/jQuery.getScript/
If you want compatibility with other libraries like prototype or mootools you can set jQuery.noConflict()
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>