Jquery onclick event Load specific node(s) of XML - javascript

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

Related

AJAX Post HTML Code

I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem

Get document information where ajax is loaded

This might not be a well formulated question, what I need is the metadata from the document where the script is begin executed not from where the data is extracted...
We have foo.com/some_title_article.html
inside of it, we have an script
<script>
(function($) {
$(document).ready(function(){
var id = data.qids;
var theTime = new Date().getTime();
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
$('#showData').html(data); // This will show a basic html form...
});
});
})(jQuery);
</script>
inside the file api.php I call a few other java scripts that are related to where that file is stored, as it is right now is working fine, but what I need is to get metadata from some_title_article.html into my other java scripts that is loaded via ajax... sortof like var currentURL = window.location.href; which is declared inside and a java script inside the api.php file, it load the full url as foo.com/some_title_article.html and not foo.com/apis/shares/api.php ...get it?., So, how can get information from the url where the ajax is executed and pass it to the other scripts that are called after the ajax script...
Does this help:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<div id="showData"></div>
<script type="text/javascript">
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
var content = data.content;
var metadata = data.metadata;
$('#showData').html(content); // This will show a basic html form...
//Then, do whatever you want to with metadata
});
</script>
You make api.php return an object where the first key is the content and the second key is the meta data.
Otherwise, if api.php returns a string that already contains meta tags in it, you would need to parse them or add them to the dom and access them that way.
Can you share a sample of what is returned by api.php?

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.

jQuery selectors on an ajax response string that is a full html page

I'm trying to get some page details (page title, images on the page, etc.) of an arbitrarily entered URL/page. I have a back-end proxy script that I use via an ajax GET in order to return the full HTML of the remote page. Once I get the ajax response back, I'm trying to run several jQuery selectors on it to extract the page details. Here's the general idea:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function (data) {
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", data);
//doesn't seem to work even if there is a title in the HTML string
var name = $(data).filter("title").first().text();
var description = $(data).filter("meta[name='description']").attr("content");
}
});
Sometimes using $("selector", data) seems to work while other times $(data).filter("selector") seems to work. Sometimes, neither works. When I just inspect the contents of $(data), it seems that some nodes make it through, but some just disappear. Does anyone know a consistent way to run selectors on a full HTML string?
Your question is kind of vague, especially w/r/t what input causes what code to fail, and how. It could be malformed HTML that's mucking things up - but I can only guess.
That said, your best bet is to work with $(data) rather than data:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function(data) {
var $data = $(data);
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", $data);
//doesn't seem to work even if there is a title in the HTML string
var name = $data.filter("title").first().text();
var description = $data.filter("meta[name='description']").attr("content");
}
});

JQuery Treeview not working with Ajax

I'm new to JQuery and web development in general. I'm trying to load some data from an XML file and build an unordered list. I've got that part working, now I'm trying to use the TreeView plugin so I can collapse/expand the data. The data is loaded like this:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "solutions.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == "string") {
// Work around IE6 lameness
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
list = ""
$(xml).find("Group").each(function() {
group = $(this).attr("name");
list += "<li><span>" + group + "</span><ul>";
$(this).find("Solution").each(function() {
solution = $(this).attr("name");
list += "<li><span>" + solution + "</span></li>";
});
list += "</ul></li>";
});
$("#groups").html(list);
},
error: function(x) {
alert("Error processing solutions.xml.");
}
});
$("#groups").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
});
and the HTML looks like this:
<html>
...
<body>
<ul id="groups">
</ul>
</body>
</html>
The unordered list shows correctly, but the little [+] and [-] signs don't show up and the sections aren't collapsible/expandable. If I get rid of my Ajax loading and insert an unordered list inside of #groups manually it works as expected.
What am I doing wrong? Is there any other plugins or Javascript libs that could make this easier? The solution needs to work on IE6 locally (i.e. webserver).
Update: I found a work-around: If I define my treeview stuff like this it works:
function makeTreeview() {
$("#container").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
}
setTimeout('makeTreeview();', 50);
I think the problem is, when I create the treeview, the ajax stuff hasn't done it's work yet, so when treeview() is called, the unordered list hasn't been created yet. I haven't tested this with IE6 yet. Is there a nicer way to do this, without using SetTimeout()?
I made the same type of call for another project.
For other reasons you will probably want to wrap your ajax call in an anonymous function to create a closure so that your variables remain what you expect them to...
The success method is a callback function that happens after your call is complete , just create your treeview inside that method, or break it out into a seperate fumction if you need to for clarity.
in the example that you show - your treeview will still fail if the ajax call takes longer than 50ms - which could easily happen during initial load if more than two objects are being loaded from that same server.
This example used JSON, and concurrently loaded html data from a page method into a series of divs.
$(document).ready(function() {
for (i= 1;i<=4;i++)
{
(function (){
var divname ="#queuediv"+i;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test12.aspx/GetHtmlTest",
data: "{}",
error: function(xhr, status, error) {
alert("AJAX Error!");
},
success: function(msg) {
$(divname).removeClass('isequeue_updating');
$(divname).html(msg);
$("#somethingfromthemsg").treeview();
}
});
})();
}
});
Hope that helps!
You need to get FireBug (Firefox add-in) and then you can see in the console what is being returned, and make sure it matches what you expect (And that it is actually doing the request..).
Once you get it working in FF, you can support the ancient 10-year old IE6 browser.
There's also some other things you may want to consider:
The whole ActiveXObject("Microsoft.XMLDOM") jumps out as me as unnecessary. If you pass XML in a string to $(), jQuery turns it into a DOM object.
Additionally, .Find can be replaced by:
$('Element', this);
So for example:
var xmlDoc = '<Group><Solution name="foo" /><Solution name="bar" /></Group>';
$('Solution', xmlDoc).each(function() {
document.write( $(this).attr('name') );
});
would spit out:
foo
bar
Also, with firebug, stick a console.log(list); at the end, to be sure you're generating the HTML you think you are. If you're really stuck in IE6, alert(list) somewhat works as a poor man's equivalent (as long as your file isn't too big).
In short, I think you're on the right track, you just need the tools to debug properly.
For anyone who also finds their way to this post. I had this trouble with an ajax call.
If you want to wait for the ajax call to be returned, you need to set async as false.
$.ajax({
type: 'POST',
async: false,
........

Categories