I'm very new to HTML.
I am trying to load an XML which contains image names and display it in a div dynamically.
I can see the image names but can't assing img a source.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","resimler.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("pic");
i=0;
function displayFoto(){
ad=(x[i].getElementsByTagName("ad")[0].childNodes[0].nodeValue);
document.getElementById("showFoto").innerHTML="img/" + ad;}
function next(){
if (i<x.length-1){
i++;
displayFoto();}}
function previous(){
if (i>0){
i--;
displayFoto();}}
</script>
</head>
<body onload="displayFoto()">
<div id='showFoto'><img id='showFoto'></img></div><br>
<input type="button" onclick="previous()" value="<<" />
<input type="button" onclick="next()" value=">>" />
</body>
</html>
Can anyone please guide me?
document.getElementById("showFoto").src="img/" + ad;
this would help you to load image but i dont garanty about rest of the code. You better look for Loader frameworks and jquery.
I agree with Kemal, just give a snipet of your xml and also the id for div and img tag is same, is that something you are unaware of it or just intentional
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
var Image = "";
x = xmlDoc.getElementsByTagName("IMAGE");
for (i = 0; i < x.length; i++)
{
Image = Image + x[i].childNodes[0].nodeValue + " ";
var res = Image.split(" ");
var ii = res[i];
var img = document.createElement("img");
img.src = ii;
img.width = 150;
img.height = 100;
document.body.appendChild(img);
}
}
}
xmlhttp.open("GET", "ll.xml", true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
</body>
Related
I'm trying to use JavaScript to display data from an XML file. My data isn't being displayed to the web page and I'm not sure why.
Any help/advice would be appreciated. My code is displayed below.
NOTE - I have no experience with XML so be aware that I am completely new to it.
<script>
var xmlData;
function loadXml () {
var filename = "CDLibrary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml () {
var CdElements;
var CdTitle;
var count;
CdElements = xmlData.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml();">
</div>
</body>
<html>
<head><title>Import XML Data</title></head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml()">
</div>
<script>
var xmlData;
function loadXml () {
var filename = "CDLibary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml(xmlDataBase) {
var CdElements;
var CdTitle;
var count;
CdElements = xmlDataBase.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</body>
</html>
You're not using the var xmlData instead you're using a var xmlDataBase. Replace you code to:
CdElements = xmlData.getElementsByTagName("CD");
And since you're using a global var xmlData, it's available inside displayXml function, in this case no need for function displayXml(xmlDataBase) if you use function displayXml() it'll be enough.
Using the w3schools link and changing some information and changing the directory I got it working. There must be an error in the template i was following, thank you all for your time and efforts.
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "CDLibrary.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("performer")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
I am just trying to prototype a simple functionality using javascript for learning purpose, but the contents within the <p> tag are not updating and I am stuck at this point. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title> Ajax Search Box </title>
<script>
function LoadList()
{
var searchBox = document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
var xHttp = new XMLHttpRequest();
searchedChars += searchBox.value;
xHttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
var xmlContent = this.responseXML;
var nameList = xmlContent.getElementsByTagName("name");
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i].textContent + "<br/>";
}
resultBox.innerHtml = dispText;
}
};
xHttp.open("GET","AssessorList.xml",true);
xHttp.send();
}
</script>
</head>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">
No Data Available.
</p>
</body>
</html>
Could someone tell me why the innerHtml is not updating? Thanks in advance.
P.S: The code is fetching the data from the xml file as I could see in browser's console, the values being passed to the dispText variable.
<!DOCTYPE html>
<html>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">No data available</p>
<script>
function LoadList() {
var xhttp = new
XMLHttpRequest();
var searchBox =
document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
searchedChars += searchBox.value;
xhttp.onreadystatechange = function() {
//alert(this.status);
if (this.readyState == 4 && this.status == 200) {
var xmlContent = this.responseXML;
var nameList = searchedChars;
alert(nameList);
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i] + "<br/>";
}
resultBox.innerHTML = dispText;
}
};
xhttp.open("GET", "ajax.txt", true);
xhttp.send();
} </script>
</body>
</html>
Hope this may help you
Here's my sample XML code:
<?xml version="1.0" encoding="UTF-8"?>
<entry n="5">
<form type="lemma">hi
<orth xml:lang="syc">ܐܳܐܱܪ</orth>
</form>
<gramGrp>
<gram type="pos">noun</gram>
<gram type="gender">commonGender</gram>
</gramGrp>
<etym>
<lang>Greek</lang>
<mentioned>ἀήρ</mentioned>
</etym>
<form type="inflected" ana="#n_pl">
<orth xml:lang="syc">ܐܰܐܷܪ̈ܰܣ</orth>
</form>
<sense>
<cit type="translation" xml:lang="en">
<quote>air, breeze</quote>
</cit>
</sense>
</entry>
I need to display this in a formatted fashion, depending on the tags. I've followed the code as found at w3schools http://www.w3schools.com/xml/xml_applications.asp, changing the filename and TagName values as necessary. In the end... nothing happens, just a blank screen. I do have a server from which I am running this, btw.
Javascript:
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
}
xmlhttp.open("GET", "dict.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("entry");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("lemma")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("sense")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
I will worry about getting all the formatting correct and all the tags represented afterwards, I just need to get it working at all, first.
I have been following a video tutorial on youtube for an AJAX upload, i know a fair amount of javascript, jquery, etc but this has me stumped.
my code is below, can anyone enlighten me as to why this is happening when i try to uploade more than one file or in some cases 1 file.
I have included my code below, its not perfect as i said i was follwoing along with a video tutorial.
<?php
if (!empty($_FILES['file']))
{
foreach($_FILES['file']['name'] as $key=>$name)
{
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'] [$key], "uploads/{$name}"))
{
$uploaded[] = $name;
}
}
if (!empty($_POST['ajax']))
{
die(json_encode($uploaded));
}
}
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="upload.js"></script>
</head>
<style type="text/css">
#upload_progress {display: none;}
</style>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded))
{
foreach ($uploaded as $name) {
echo '<div>'.$name.'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" multiple="multiple">
<input type="submit" id="submit" value="upload">
</form>
</body>
</html>
And my JS file is
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i)
{
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes())
{
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert("Upload Failed");
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if (this.status == 200)
{
var links = document.getElementById('uploaded');
console.log(this.response);
var uploaded = JSON.parse(this.response);
var div, a;
for (var i = 0; i < uploaded.length; i++)
{
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'uploads/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log("error" + this.response);
}
}
});
request.open('POST', 'index.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
Initially the video had me using eval for the variable uploaded, i changed this to JSON.parse, i don't want a quick fix but rather an answer as to why this isn't working?
Thanks
Ben
I found out what the problem was, inside the php.ini file there is a size restriction on my server for file uploads, i increased that and it works fine now.
Anyone else who has the same problem check your upload size!
I was following a tutorial about how to make an javascript/ajax upload system with progress (%) indicator . I have successfully added a css progress bar indicator to it .
But i have a problem that i can't solve is how to put to condition of upload like: type, file size, file is set, ....
here is my code (upload.php)
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
and this is the javascript file (upload.js):
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
I just need and example of how to check file size is less than 50MB and i can do the other checks my self i just don't know how to check condition in this upload system.
Thanks in advance
If you want to check something like the size, you can realize it with your code easily:
Take a look at these lines in your code:
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
This is where the files are added to the FormData which is then submitted to the server. You can add the conditions here, e.g. a size check:
for (var i = 0; i < fileInput.files.length; ++i){
//file.size is given in bytes
if(fileInput.files[i].size <= MAX_FILESIZE_IN_BYTES){
data.append('file[]', fileInput.files[i]);
}
}
I hope this helps.