Alternatives for jQuery .html() method? - javascript

I am currently developing a single page application, using phonegap. What i am trying to realize is to initially parse a xml file and store the content for further usage.
At the moment everything works fine but there is one major problem:
Within my xml file there is a a tag which contains html formatted text content. For example:
<textfield> <h1>Title</h1> Content </textfield>
What i currently do is to load my xml file via jQuery ajax call and then use the html() method to retrieve my textfield html:
this.description = $(Obj).find("textfield").html();
On Google Chrome, Firefox and Android this works fine. The html is stored an can later be appended to my objects. However on Safari and therefore on Iphone devices the html() does not work. Now i am looking for a workaround. I certainly do not want to use text() because my formatting will be ignored.
EDIT: My ajax call:
$.ajax({
type: "GET",
url: Controller.baseURL+"/"+name+".xml",
async: false,
timeout:3000,
dataType: "xml",
success: function (data) {
alert("succ");
xml = data;
},
error: function () {
alert('error!');
}
});
Maybe someone can help me.
Thanks in advance

var parser = new DOMParser();
var parsed = parser.parseFromString(yourXMLStringLoadedViaAjax, 'text/xml');
var textfieldConetent = parsed.querySelector('textfield').innerHTML;

After a few hours of search I finally found my answer here:
https://stackoverflow.com/a/25789924/3566334
It seems that
In IE 9, 10 and 11, Safari 7.0 and Opera 12, the nodes in doc have neither an innerHTML field nor an xml field
I followed the advice of using XML Serializer and it works like a charm!

Related

Javascript getting XMl data from external source

I am trying to read the XML of an RSS feed on a website (that I do not have control over) and display it using Javascript. I used the following code to extract the data and it works, but the major caveat is that this will only work in IE 8 (Ugh).
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",<URL with xml extension>,false);
xmlhttp.send();
setTimeout("wait()",3000);
function wait()
{
alert("complete");
}
var xmlDoc = xmlhttp.responseXML;
var data = xmlDoc.getElementsByTagName("entry");
The wait function currently exists to give the server time to respond to my xmlHTTP request. Does anyone know a workaround in Javascript, AJAX or something similar that would give me functionality on current versions of Firefox, Chrome, etc?
I think you should use JFeed, its faster and its really easy to use, your code is a bit long, with Jfeed you can do it like that:
jQuery.getFeed({
url: '<URL with xml extension>',
success: function(feed) {
alert(feed.entry); //your element
}
});
let me know if you need help with that.
Good luck.

jquery load() equivalent for offline use

I am looking for an equivalent to jquery's load() method that will work offline. I know from jquery's documentation that it only works on a server. I have some files from which I need to call the html found inside a particular <div> in those files. I simply want to take the entire site and put it on a computer without an internet connection, and have that portion of the site (the load() portion) function just as if it was connected to the internet. Thanks.
Edit: BTW, it doesn't have to be js; it can be any language that will work.
Edit2:
My sample code (just in case there are syntax errors I am missing; this is for the files in the same directory):
function clickMe() {
var book = document.getElementById("book").value;
var chapter = document.getElementById("chapter").value;
var myFile = "'" + book + chapter + ".html'";
$('#text').load(myFile + '#source')
}
You can't achieve load() over the file protocol, no other ajax request is going to work for html files. I have tried even with the crossDomain and isLocale option on without anything success, even if precising the protocol.
The problem is that even if jQuery is trying the browser will stop the request for security issues (well most browsers as the snippet below works in FF) as it allows you to load locale file so you could get access to a lot of things.
The one thing you could load locally is javascript files, but that probably means changing a lot of the application/website architecture.
Only works in FF
$.ajax({
url: 'test.html',
type: 'GET',
dataType: 'text',
isLocale: true,
success: function(data) {
document.body.innerHTML = data;
}
});
What FF does well is that it detect that the file requesting local files is on the file protocol too when other don't. I am not sure if it has restriction over the type of files you can request.
You can still use the JQuery load function in this context:
You would could add an OfflineContent div on your page:
<div id="OfflineContent">
</div>
And then click a button which calls:
$('#OfflineContent').load('OfflinePage.html #contentToLoad');
Button code:
$("#btnLoadContent").click(function() {
$('#OfflineContent').load('OfflinePage.html #contentToLoad');
});
In the OfflinePage.html you could have to have another section called contentToLoad which would display on the initial page.

How can I extract part of an XML document using jquery to be transformed (xslt)?

I want to know how can I extract part of an XML document using jquery to an object, which will be transformed via XSLT? So, let's say I have this sample XML document:
<nutrition>
<daily-values>
<total-fat units="g">65</total-fat>
<saturated-fat units="g">20</saturated-fat>
<cholesterol units="mg">300</cholesterol>
<sodium units="mg">2400</sodium>
<carb units="g">300</carb>
<fiber units="g">25</fiber>
<protein units="g">50</protein>
</daily-values>
<food>
<name>Avocado Dip</name>
<mfr>Sunnydale</mfr>
<serving units="g">29</serving>
<calories total="110" fat="100"/>
<total-fat>11</total-fat>
<saturated-fat>3</saturated-fat>
<cholesterol>5</cholesterol>
<sodium>210</sodium>
<carb>2</carb>
<fiber>0</fiber>
<protein>1</protein>
<vitamins>
<a>0</a>
<c>0</c>
</vitamins>
<minerals>
<ca>0</ca>
<fe>0</fe>
</minerals>
</food>
<food>
<name>Bagels, New York Style </name>
<mfr>Thompson</mfr>
<serving units="g">104</serving>
<calories total="300" fat="35"/>
<total-fat>4</total-fat>
<saturated-fat>1</saturated-fat>
<cholesterol>0</cholesterol>
<sodium>510</sodium>
<carb>54</carb>
<fiber>3</fiber>
<protein>11</protein>
<vitamins>
<a>0</a>
<c>0</c>
</vitamins>
<minerals>
<ca>8</ca>
<fe>20</fe>
</minerals>
</food>
</nutrition>
Let's say I just want the first < food >...< /food > block and I wish to save it as an object or a string. How can this be done using jquery? Once I have the XML block extracted, I can properly combine with a XSL document for transformation (XSLT). Thank you very much for any help!
UPDATE; CLARIFICATION:
I apologize if my question is not clear. Please allow me to clarify my position.
I am well aware that XML can be manipulated by using the browser's DOM and the differences between IE and non-IE implementations. I can use methods like cloneNode and selectNodes on an XML Object. In fact, that's how I have done it. Now if I bring jQuery into the equation, I'd like to replace all those lines of code with a jQuery way of dealing with it. That is, perhaps there's a jQuery plugin that eliminates the need to directly interact with the XML DOM for each browser, taking care of cross-compatibility "behind-the-scenes". I'm looking for a js framework that will take care of everything for me, instead of how I am dealing with it at the moment, which is separate implementations for IE and non-IE browsers.
I hope that clarifies my question.
Thank you very much for any help.
With jQuery.parseXML(xmlString) you can convert an XML string to a
jQuery object, then do whatever you want with that.
OR
If it's an XML file, you can GET it via AJAX
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
error: function(){},
success: function (xml) {// you can access the parsed XML just like you do it with HTML }
});
In compatible browsers you can convert a document object or fragment to XML using an XMLSerializer:
var d = document.createElement('div');
d.id = 'div0'
var p = d.appendChild(document.createElement('p'));
var xmlString = (new XMLSerializer()).serializeToString(d);
alert(xmlString);
// shows <div xmlns="http://www.w3.org/1999/xhtml" id="div0"><p></p></div>
A little more work in IE, but not much. You need to create an XML object of just the bits you want, then get it's xml property:
alert(xmlObject.xml);
After doing some research, it appears even those within the jQuery community recommend XML manipulation to be done by the browser, as it is usually faster.

jquery append not working in IE/Firefox

I have the following HTML and subsequent jQuery which appends the related HTML elements after the JSON request has been retrieved.
This implementation works in Google Chrome + Android browser + Safari, but is not populating the data in Firefox or Internet Explorer 9.
** Works in Chrome, Android browser, Firefox 4 ... does not work in Firefox 3.x and IE.
Static HTML:
<header class=line>
<div class="unit size3of4">
<h2 class="fullname"></h2>
<h4 class="nickname"></h4>
</div>
</header>
The jQuery code:
<script>
function load_user_info() {
var content_url = 'rest.api.url.com';
$.getJSON(content_url, {id:'11xx1122xx11'}, function(data){
console.log(data);
$.each(data, function(key, value) {
if (key == "fullname") {$('.fullname').append(value);}
else if (key == "nickname") {$('.nickname').append(value);}
});
});
}
load_user_info();
</script>
Slightly confused about the behavior between browsers. I can guarantee the JSON request is returning two variables: fullname & nickname and have confirmed this
In Firefox using the FireBug plugin I see the results of console.log(data).
In Chrome I see the results of the console.log(data) and the successful display of the fullname & nickname in the HTML after the JSON request.
Using jQuery 1.6.1 if it helps ...
JSON Output:
{"fullname":"johnny fartburger", "nickname":"jf"}
I'm slightly perplexed by what you're doing. I think the following code:
$.each(data, function (key, value) {
if (key == "fullname") {
$('.fullname').append(value);
} else if (key == "nickname") {
$('.nickname').append(value);
}
});
could be more easily represented by this:
$('.fullname').append(data.fullname);
$('.nickname').append(data.nickname);
I don't know if this will solve your problem, but it would certainly be an improvement.
The resulting problem was from the actual JSON data not being retrieved in IE. Hours and hours of search turned up the problem was that XDomainRequest is not natively supported by jQuery, specifically in a $.getJSON request
http://bugs.jquery.com/ticket/8283
In the end, I wrote a try {} catch {} statement that checks to see if $.browser.msie and if it is, do not use $.getJSON to retrieve the results, rather:
if ($.browser.msie) {
var xdr = new XDomainRequest();
xdr.open('GET', url);
xdr.onload = function() {
var data = $.parseJSON(this.responseText);
show_data(data);
}
xdr.send();
} else {
$.getJSON(url, function(data){
show_data(data);
});
}
So ... conclusion append does work in IE (7/8/9) and Firefox (3/4) but not when the AJAX results aren't being returned. Thanks everyone for your help and insight.
.append(value) is not very safe (for example if value="div").
You should use .html(value)
And what does data contain? I think .append is used to append elements. If data is plain text, that might not work (haven't tried it actually). Chrome uses a different engine and may convert the text to a textnode in the DOM.
Use .text() or .html() to set the contents of an element.
as an alternative with appendTo, try to use .text() too
.append() takes a HTML string as a parameter to append to the existing content. You probably want to replace the element's text, use .text() or .html() instead, depending on the contents of the value variable.

Javascript works in FF / IE but not Chrome / Safari

I'm working on a Drupal 6 module where I use jquery (and more specifically, the $.ajax method) to retrieve a RSS feed from Yahoo's weather API. I decided against using the JFeed library because I need access to the elements with "yweather" prefix (and I couldn't find a way of accessing them via JFeed). I decided to use the $.ajax method and parse the XML response instead. The JavaScript code below works fine in Firefox and IE but does not work in Safari (or Chrome FWIW):
function parseXml(xml) {
var atmosphere = xml.getElementsByTagName("yweather:atmosphere");
var humidity = atmosphere[0].getAttribute("humidity");
$('#weatherFeed').html("Humidity: " + humidity);
$('#weatherFeed').append(
"<div style=\"text-align: center;margin-left: auto; margin-right: auto;\">" +
city + ", " + state + "</div>");
}
function getData(){
$.ajax({
type: 'GET',
url: 'proxy.php?url=http://weather.yahooapis.com/forecastrss&p=94041',
dataType: 'xml',
success: function(xml) {
parseXml(xml);
}
});
}
if(Drupal.jsEnabled) {
$(function() {
getData();
setInterval("getData()", 30000);
});
}
When I check the error console in Safari I see the following error message: TypeError: Result of expression 'atmosphere[0]' [undefined] is not an object. Is there an issue with using getElementsByTagName in Safari? Should I be accessing the object that's returned by getElementsByTagName differently?
Maybe just treating the the XML as data and using jQuery selectors to pull out what you want would work.
$(xml).find("yweather:atmosphere").attr("humidity") - you might need to use filter instead of find - what do you think?
I had the exact same problem, but came across the answer here:
http://reference.sitepoint.com/javascript/Document/getElementsByTagName
It has to do with the yweather namespace. Use getElementByTagNameNS function instead.
var atmosphere = xml.getElementsByTagName("yweather:atmosphere");
becomes
var atmosphere = xml.getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0","atmosphere");
function reference:
http://reference.sitepoint.com/javascript/Document/getElementsByTagNameNS
Have you tried atmosphere[1] instead of 0 for Chrome and Safari?

Categories