First AJAX project...(wont load text file inline) - ajax

This is my first time working with AJAX, and I cant seem to figure out WHY the .txt file will NOT load? but instead goes to a new page with just that text displayed) ie: not loading in the same page:
my index.html page:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<script src="js/main.js"></script>
</body>
</html>
here is my main.js script:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
in my ajax.txt file.. I just have some random plain text: This is Ajax text to be loaded.
I am NOT running this locally, but through localhost using WAMP web server..
What am I missing? or overlooking here?
Tutorial link: tutsplus.com/lesson/the-simplest-ajax-script

to solve your problem:
Make this replacement to your code:
onClick -> onclick (js is case sensitive)
readystatechange -> onreadystatechange
then put this piece of code out of the onreadystatechange function:
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
This is the new main.js:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onclick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
return false;
};
//open the request
xhr.open("GET", "files/ajax.txt?aiai", true);
//send the request
xhr.send(null);
return false;
};
})();
alert(message);

I think its easier to do it like that:
first, HTML:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<div id="textFiles"><!-- files display here --></div>
</body>
</html>
JS:
<script>
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function loadText() {
var message = "Test";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("textFiles").innerHTML = xmlhttp.responseText;
alert(message);
}
else{
document.getElementById("textFiles").innerHTML = "Loading Files...";
}
};
xmlhttp.open("POST",'files/ajax.txt',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>

Related

XML data pasing

Hi I am trying to display data from XML file to unordered list. Any help would be great. I do have an XML file books data wherein trying to print or display the books author etc.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
report(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function report(xml){
var i;
var xmlDoc=xmlhttp.responseXML;
var table = "";
var x = xmlDoc.getElementByTagName("CD");
for(i=0; i<x.length; i++){
table+="<li>" + x[i].getElementByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</li>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
<body>
<ul id="demo"></ul>
<button type="submit" onclick="loadDoc()">RUUUUNNNNN</button>
</body>
</html>

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

upload progress div increase

function uploadToServer(){
fileField = document.getElementById("uploadedFile");
var fileToUpload = fileField.files[0];
var xhr = new XMLHttpRequest();
var uploadStatus = xhr.upload;
uploadStatus.addEventListener("progress", function (ev) {
if (ev.lengthComputable) {
$("#uploadPercentage").html((ev.loaded / ev.total) * 100 + "%");
}
}, false);
uploadStatus.addEventListener("error", function (ev) {$("#error").html(ev)}, false);
uploadStatus.addEventListener("load", function (ev) {$("#error").html("sorry!")}, false);
xhr.open(
"POST",
"serverUpload.php",
true
);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", fileToUpload.fileName);
xhr.setRequestHeader("X-File-Size", fileToUpload.fileSize);
xhr.setRequestHeader("X-File-Type", fileToUpload.type);
//xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(fileToUpload);
}
$(function(){
$("#uploadButton").click(uploadToServer);
});
`
<form action="" name="uploadForm" method="post" enctype="multipart/form-data">
hi this code is working fine. but i need increase div size. but this one only showing percentage only. what i have to change to get dat one.
bellow is simple progressbar code using HTML5
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<span id="status"></span>
<h1 id="finalMessage"></h1>
<script type="text/javascript" language="javascript">
function progressBarSim(al) {
var bar = document.getElementById('progressBar');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var sim = setTimeout("progressBarSim("+al+")",300);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "Process is complete";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
</script>
it may help you, fix this code in your coding.

Change content of div onclick with Ajax

I want to change the content the div named john to the output from the php file when an image is clicked. I'm sure it's simple but I can't find an example that fits. Here's my code:
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send(null);
}
html
<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>
test.php
<?php echo "hello"; ?>
Looks to me like you've got a syntax error with your javascript. Your trying to get the responseText from xmlhttp but your XMLHttpRequest is stored in ajaxRequest
Try this
function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
document.getElementById("john").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send();
}
may I suggest for cross browser/version, use:
var ajaxRequest = getXMLHttpRequest();
and then,
function getXMLHttpRequest() {
var re = "nothing";
try {re = new window.XMLHttpRequest();} catch(e1) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
if (re != "nothing") {return re;}
else {return null;};
};
as well as changing it to
ajaxRequest.responseText();
I've managed to solve it with the code below. This code also returns the ID of the element after getting "hello" from the php file.
<script language="javascript">
function calldislike(str){
if (str==""){
document.getElementById("john").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>
test.php
<?php echo "hello".$_GET["q"]; ?>

Convert normal links to Ajax dynamically

I have put together some code from various sources but javascript is somewhat unknown to me and I only seem to fail with the code I have so far..
What I want to do is convert every normal link on the page to ajax links and load the pages through ajax.
So far I only succeeded to transform the links from the initial page and load the content in a div. The problem is I don't have access to the content is loading in the div and the new content still has normal links instead of ajax.
Is there a way I can convert the new links within the content loaded in the div, every time the div changes?
Also what I don't know is, if the user clicks on the home button in the menu, it will load the content of index along with this script, and everything will become a loop. How can I prevent the code from loading in index if it loads inside the div?
If you suspect any other problems it may occur from this code can you please advice me what to change?
This is the code I have so far..
Thank you very much for any advice!
Inserted in the head tag:
<script type="text/javascript">
var xmlhttp;
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
}
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
</script>
Inserted somewhere in the body:
<div id="contentarea"></div>
Inserted right before the body ends:
<script>
var oP = document.getElementsByTagName("a");
var ctr=0;
while(ctr < oP.length){
var oldHref = document.getElementsByTagName("a")[ctr].href;
document.getElementsByTagName("a")[ctr].href="javascript:loadPage('"+oldHref+"');";
ctr++;
}
</script>
here ja go.. whipped this up for you.. you can use document.links to get all anchor tags. I'm doing this on 'contentArea' only. Everything inside (function () { will only be called when the document is ready. Then, in the onreadystatechange event I call the function again to set the click event on any anchors that are returned in the resposne.
<script type="text/javascript">
var xmlhttp;
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
var parseAnchors = function(){
var anchors = document.getElementById("contentarea").links; // your anchor collection
var i = anchors.length;
while (i--) {
var anchor = anchors[i];
anchor.onclick = (function(url) {
return function() {
loadPage(url);
return false;
};
})(anchors[i].href);
anchor.href = "#";
}
};
(function () {
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
parseAnchors();
}
window.onload = function () {
parseAnchors();
}
</script>

Resources