I am trying to get a feel for adding content to a page with XMLHTTPRequest. I would like to add the results to existing page content say in a second column, but I am not having any luck. I would appreciate a shove in the right direction. Thanks for any help.
<!DOCTYPE html>
<html>
<head>
<style>
#button{
float: left;
}
#team{
float: left;
}
</style>
<title>XMLHTTPRequest</title>
<script src="jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseXML;
var team = xmlDoc.getElementsByTagName("teammember");
var html = "";
for (i = 0; i < team.length; i++){
html +=
xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue + "<br><br>";
}
//this is the code I would like help with
var team = document.getElementById("team");
team.appendChild(document.createTextNode("html"));
}
}
xhr.open("GET", "team.xml", true);
});
</script>
</head>
<body>
<div id="button">
<button onclick="xhr.send()">Click Me!</button>
</div>
<div id="team">
</div>
</body>
</html>
I wrote a script fairly similar to yours that does nearly exactly what you are on about. Below is the some normal JavaScript I used to put it all on the page, I have changed some of the variable names so it compares nicely with your code.
for (i=0; i<team.length; i++)
{
//Create text nodes for each element as that's what appendChild() needs
var nameText = document.createTextNode(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue);
var titleText = document.createTextNode(xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue);
var bioText = document.createTextNode(xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue);
//This div will contain one team member's info
var memberDiv = document.createElement('div');
//Add text to the div created
memberDiv.appendChild(nameText);
//Line break
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(titleText);
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(bioText);
//Add the div we've just created to the document.
document.getElementById('team').appendChild(memberDiv);
}
This may need some more adapting to suit your needs but you get the general idea. This is just one way of doing it, there's probably loads of other ways including with jQuery that may be a bit neater actually.
You can use memberDiv.setAttribute('class', className) to set the class of each div to whatever you want
Below is a visual representation of this code to make it easier to understand, click for full scale (500*1750):
Related
I want to develop a News Ticker using three technologies: PHP, Javascript and AJAX.
First, I made a PHP function getFeed() to fetch data from News websites on an Array, then I made a JSON return using this code: echo json_encode($articles, true);
Secondly, I aim to use AJAX and Javascript to make repeated calls to getFeed() function, here is my javascript code:
<script type="text/javasript">
var xmlhttp=false;
function begin() {
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200){
var jsonContent=JSON.parse(this.responseText);
displayT(jsonContent);
}
};
// rssnews.inc.php contain the getFeed() function
xmlhttp.open('GET','rssnews.inc.php', true);
xmlhttp.send();
}
// displayT(content) function display the JSON element
function displayT(content){
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<h4><a href="' + arr[i].link+ '">' +
arr[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}
</script>
On the HTML page, I have the following components a button (id="start") - on click execute begin() function, a div container (id="Ticker") and a div (id="item") for display data with AJAX
<form>
<button type="submit" class="btn btn-default" id="start" onclick="begin();"> START </button>
</form>
<div id= "ticker" style="border: 1px solid #ccc; height: 500px; weight:600px;">
<div id="item">
<!-- I want to display the fetched data by 4 items at a specific time Interval-->
</div>
</div>
When I click on the start button, I don't get the json data.
How can I solve this problem and how can I ensure that this AJAX calls is the most appropriate way to my Ticker.
Thank you!
The error is essentially saying that the file you are trying to GET with you AJAX call, does not exist at the specified location (which is http://localhost/rss/rssnews.inc.php).
You are using a Relative path, which searches for 'rssnews.inc.php' in the same folder. To go up to the parent directory, use ../.
Or use an Absolute path, as in http://localhost/rss/rssnews.inc.php. (Replace with absolute path to your PHP script)
Update
(after HTTP 401 solved)
displayT function is taking content as input, and is then reffering to arr, which is not defined.
Assuming content is actually an array containing your data in the desired format, replace arr with content:
function displayT(content){
var out = "";
var i;
for(i = 0; i < content.length; i++) {
out += '<h4><a href="' + content[i].link+ '">' +
content[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}
My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}
First, I am not a programmer anymore... It's been years since doing it and even then it was only VBA and old school HTML.
What I would like to do is to show an image on my site in place of another depending on it's "state". For example, the site is http://w2zxl.hevener.com/ , towards the bottom of the page is a script that loads a HAM radio logbook as well as my current status in nearly real time. If I am on the Air, it will show a small image that says "On Air" and then show what frequency I am on and the Mode I am working in. When I am off the air however, that little image just disappears and shows nothing.
What I would like to do is to create a small image to replace the "nothing". In other words, if I am Off Air, I would like to show an "Off Air" image instead of nothing at all.
Is there an If/Then/Else statement that can do this given the code I am providing below?
Code below:
<!-- HRDLOG.net script start --><center>
<div id="hrdlog-oa"> </div>
<div id="hrdlog">www.hrdlog.net</div>
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
<script type="text/javascript" language="javascript">// <![CDATA[
var ohrdlog = new HrdLog('W2ZXL');
setInterval('ohrdlog.LoadOnAir()', 5000);
ohrdlog.LoadLastQso(10);
// ]]></script>
<img src="http://www.hrdlog.net/callplate.aspx?user=W2ZXL" alt="W2ZXL CallPlate" /></center><!-- HRDLOG.net script stop -->
Consider swapping CSS classes to change the background-image instead. This will simplify the javascript and html markup. When you're on air change the class to onair and toggle as needed to offair.
CSS
.onair {
background-image: url("onair.jpg");
}
.offair {
background-image: url("offair.jpg");
}
Html
<div id="hrdlog-oa" class="offair"></div>
Javascript
var statusDiv = document.getElementById("hrdlog-oa");
if (statusDiv.className == "offair") {
statusDiv.className = "onair";
}
else {
statusDiv.className = "offair";
}
Working jsfiddle http://jsfiddle.net/jasenhk/qMAZU/ using background-color instead.
You can not do that with pure HTML and you had 2 way for solving this
If you like markup languages you can use xsl that have if else tag for you
Using Javascript and check if you be on air show on air image and if you not be shows off air
for you the better way is change some javascript code in your site..
you should overwrite ohrdlog.LoadOnAir then you have two way again:
change http://www.hrdlog.net/hrdlog.js source code and rewrite LoadOnAir function
overwrite LoadOnAir function with inserting script tag after load http://www.hrdlog.net/hrdlog.js
i choose number 2 for you because i think you can`t change script that you load it from another domain address... now you should insert this code after this part:
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
and you can found link of offair image in HrdLog.prototype.ShowOffAir function that now, i point it to http://2.bp.blogspot.com/_Dr3YNV7OXvw/TGNNf561yQI/AAAAAAAABIk/-E2MB4jLP_o/s400/Off-Air.jpg:
<script type="text/javascript" language="javascript">
HrdLog.prototype.ShowOffAir = function() {
return '[<img src="https://i.stack.imgur.com/WEr1B.jpg" height="33" width="65" />][2]';
}
HrdLog.prototype.LoadOnAir = function() {
var t = this;
var async = new Async();
async.complete = function(status, statusText, responseText, responseXML, obj) {
if (status == 200) {
txt = '';
var xmldoc = responseXML;
var onairdoc = xmldoc.getElementsByTagName('OnAir');
if (onairdoc.length == 1) {
onair = onairdoc.item(0);
if (onair.getElementsByTagName('oa_QRZ').length > 0) {
txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
txt += '<b>';
txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + ' ';
try {
txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
} catch (e) { }
//txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
}else{
txt += t.ShowOffAir();
}
}else{
txt += t.ShowOffAir();
}
element = document.getElementById('hrdlog-oa');
if (element != null) {
element.innerHTML = txt;
}
} else {
alert('Error\n' + statusText);
}
}
if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
this._lastLoadOnAir = new Date();
async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
}
}
</script>
I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.
I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>