How to stop my xml file duplicating on refresh but renewing instead? - javascript

I have this xml file which has text init.
i.e
Hi my name is steven
When i add a Setinterval to load the xml file every 10 seconds i get
Hi my name is stevenHi my name is stevenHi my name is stevenHi my name is steven
This continues duplicating every 10 seconds
Here is my javascript xml function
myLoadInteval = setInterval(Xml, 10000);
function Xml(){
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.mobilefriendlywebapps.co.uk/tayloredtest1/note.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("menu").each(function() {
//find each instance of loc in xml file and wrap it in a link
$("div#site_list").append( $(this).find("cd").text() );
$("div#treatments").append( $(this).find("cd1").text() );
$("div#preparation").append( $(this).find("cd2").text() );
$("div#products").append( $(this).find("cd3").text() );
$("div#info").append( $(this).find("cd4").text() );
$("div#price").append( $(this).find("cd5").text() );
$("div#promo").append( $(this).find("cd6").text() );
});
}
});
}
How do i remove the old xml before the new on loads?

Rather than using append() use html()
i.e
$("div#site_list").html( $(this).find("cd").text() );

If I've understood right, you're getting duplicate content because you're appending to the HTML elements each time, not emptying them first. If you want to replace the contents, do just that, rather than appending. So:
$("div#site_list").append( $(this).find("cd").text() );
...would become
$("div#site_list").text($(this).find("cd").text());
Or, if you XML contains CData-protected HTML mark-up, use the html() method instead.

Related

Jquery onclick event Load specific node(s) of XML

I need to find a way to pass the correct input to this javascript function to have it search an XML document and return the requested node value(s). The parsing of the XML node values actually does work properly when hard-coded as seen below and I can successfully load content using the following:
function parse(document){
Lyrics2 = $(document).find('elementRef[id="2"] content').text()
Ref2 = $(document).find('elementRef[id="2"] bibleRefs').text()
$("#content").text(Lyrics2);
$("#scripture").text(Ref2);
};
$.ajax({
url: 'songlyrics.xml',
dataType: "xml",
success: parse
});
The problem is I want to pass an additional parameter to the parse function that searches for somnething else in the XML. The ultimate goal is to have a div updated on the page with modified content from the XML document once a link is clicked, for example, something like this (where 'reference' is the search string passed in):
function parse(document,reference){
Lyrics2 = $(document).find(reference).text()
$("#content").text(Lyrics2);
};
...
<div id="content"></div>
Title
What is happening is the text that is present on page load is replaced with nothing after clicking a link that has onClick specified to run the 'parse' function--no errors are generated in the debug window.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<elements>
<elementRef id="1">
<name>John</name>
<artist>Smith</artist>
<content>Active</content>
<supportImg>test1</supportImg>
<bibleRefs>Mark 2:13</bibleRefs>
<other>Mark 2:11</other>
</elementRef>
<elementRef id="2">
<name>Jane</name>
<artist>Smith</artist>
<content>Active</content>
<supportImg>test2</supportImg>
<bibleRefs>John 3:17 Mark 12:3</bibleRefs>
<other>October, 2011</other>
</elementRef>
</elements>
Please let me know if you need more information in order to help. Any help is GREATLY appreciated.
I think what you are looking for is
function parse(reference) {
if (!xml) { //the ajax request is not yet loaded so there is nothing to do
return;
}
var content = $(xml).find(reference).text()
$("#content").text(content);
};
var xml;
$.ajax({
url: '
songlyrics.xml ',
dataType: "xml",
success: function (doc) {
//assign the loaded xml content to a gloabl variable so that it can be used later
xml = doc;
}
});
then
Title

JQuery's ajax function stripping HTML tags from XML

Okay, I'm pulling data from an XML file to populate my elements of my webpage dynamically. My problem is that when I use JQuery .ajax to pull the xml file, it strips my HTML tags.
For example,
Data in XML file:
<transcript><p>Hello, world</p></transcript>
Desired output on webpage:
<p>Hello, world</p>
Actual output:
Hello World
Here is my code inside of my ajax function:
$(xmlData).find('item').each(function() {
var n = $(this).find('transcript').text();
I've tried to use JQuery's '.html()' but it returns null. What is the simplest way I can fix this? Preferably without changing too much of what I've already done.
Thanks in advance.
Using text will strip the tags as you experienced. You can instead use the jQuery children method (reference) on the transcript node to get the HTML. Here is a working example: http://jsfiddle.net/gjwyd/
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: "<transcript><p>Hello, world</p></transcript>"
},
success: function(xml) {
var container = $('#content');
var html = $(xml).find('transcript').children();
container.html(html);
}
});
});​
The key is this line:
var html = $(xml).find('transcript').children();
And being sure to set the dateType as xml.
Issues
When taking HTML from an XML response it may be missing the default styles. For example, a paragraph tag may not have display: block. Resetting the styles may be one way around this issue. A more correct and probably easier way would be to put the HTML content inside of CDATA within the XML as one of the other commenters suggested.
http://jsfiddle.net/tZJQp/
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: "<transcript><![CDATA[<p>Hello, world</p><p>Bye</p>]]></transcript>"
},
success: function(xml) {
var container = $('#content');
var html = $(xml).find('transcript').text();
container.html(html);
}
});
});
As others note, html won't work on XML.

get all images in an HTML string

I'm always having trouble with that,
i'm loading a file with AJAX :
$.ajax({
url: fullHref,
success : function(result) {
console.log(fullHref+" was loaded via AJAX");
saveImages(result);
}
});
and trying to iterate through all images in result :
function saveImages(file){
console.log("savesImages enterd");
$(file).find('img').each(function(){
console.log("The file has this image : "+$(this).attr('src'));
});
}
}
I've also tried :
$('img',file)
$('img',$(file))
$('img',$(file).html())
Yet it doesn't enter the loop.
Any suggestions?
I'm using Chrome, and i don't wanna use regex.
Tryfilter() instead of find:
$(file).filter('img').each(function() { /* ... */ });
find() looks down the DOM tree which is not what you want if the img elements in the string are all at the root level.
Just make a new node and set the innerHTML of it.
$('<span></span>').html(file).find('img').each(...

Get HTML source code as a string

I want the source code of an HTML page (1.html) to be used in another page (2.html). Furthermore, I want to perform operations on it in 2.html.
Is there a way to do this?
EDIT: 1.html is a separate public webpage and I do not have access to make changes to its source code. I have to do whatever I need only by using 2.html.
To get the DOM converted to a string:
document.getElementsByTagName('html')[0].innerHTML
Question: what do you mean by "use it"? Do you need to include 1.html inside 2.html? Or do you just need to process it?
Its very simple
On 2.html use this jQuery snippet
$.get("1.html", function(response) {
alert(response)
//do you operations
});
jQuery:
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
I don't understand whatyou mean that you must make modifications, but you could simply load the second page through AJAX
var url ="1.html";
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
}
});
Use can use .html method alternatively to get the entire html data of the page.
$(function(){
var a = ($('html').html())
})​
A realy simple and modern way is the follow:
fetch('1.html').then(function(response) {
/* when the page is loaded convert it to plain text */
return response.text()
}).then(function(html) {
/* initialize the DOM parser */
var initParser = new DOMParser();
/* parse the text */
var parse = initParser.parseFromString(html, 'text/html');
/* you can now even select part of that html as you would in the regular DOM */
/* example */
var docOutput = parse.querySelector('html').outerHTML;
console.log(docOutput);
}).catch(function(error) {
console.log('Error fetch page: ', error);
});

Why .html() method does not load data in the element?

$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").html("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").html(data_aj);
}
});
I really have tried everything but can't figure out whats wrong. If I use alert(data_aj); it gives the desired output and just works fine but HTML(data_aj) just doesnt loads into a <ul> element #list using .html(). Can anyone tell me why?
Have you tried putting your code in a document ready, as your alert will fire fine but if your dom is not loaded then you cannot append to it. Also use .append() for lists not html
$(document).ready(function() {
$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").append("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").append(data_aj);
}
});
});
Listen up...
$.get() is a shorthand for $.ajax().
So when you do this
$.get(uri, function(data){
//Your functionality
});
You're really doing this
$.ajax({
url: uri,
type: "GET",
success: function(data) {
//Your functionality
}
});
By default this returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. As you are requesting a .txt file it will interpret it as a simple textfile. If you want to tell it what you would like to return (HTML), you can either do it in the MIME-type on the server page, or you could use $.getJSON().
An easy way to solve this is thus doing:
$.get(uri, function(data) {
//Your functionality
},
"html");
Which is the same as doing:
$.ajax({
url: uri,
type: "GET",
dataType: "HTML",
success: function(data) {
//Your functionality
}
});
Also it is not a good idea to use html() because you are replacing the existing html inside of your ul element every time you want to add an additional new node.
Try making use of:
$('#list').append('<li>' + data_aj + '</li>');
Basically you can just append the <li> to the <ul> itself.
Lastly make sure your dom has already been loaded by placing all your JQuery code into the
$(document).ready(function() {
//Your code...
});
Otherwise if your HTML is not fully loaded yet, your list might not exist yet so there is no way for JQuery to put some values into unexisting HTML.

Categories