Update link text with content from XML document - javascript

For each link, e.g.
http://www.wowhead.com/item=78363
I'd like to retrieve the ID at the end of the URL in the href attribute. For example, 78363, as seen above. Using this ID, I'd like to retrieve an XML page and get data from it based on the ID. The URL of the XML document is the same as the link to the item, but ending with &xml, so:
http://www.wowhead.com/item=78363&xml
From XML page I need the value inside the CDATA section seen below:
<name>
<![CDATA[Vagaries of Time]]>
</name>
That is, "Vagaries of Time". Then I need to insert the name inside the tag:
Vagaries of Time
How can I accomplish this?

Loop through the links based on a regular expression, send an Ajax request, parse the text using regular expressions, and done.
$('a').each(function() {
var $this = $(this);
if(/item=\d+$/.test(this.href)) {
$.ajax({
url: this.href + '&xml',
dataType: 'text',
success: function(data) {
$this.text(/<!\[CDATA\[([^\]]+)/.exec(data)[1]);
}
});
}
});
You'll most likely want to add some error-checking, of course. Also, if your XML document is more complex than the example you posted, consider parsing using the native XML capabilities instead - I just used a regular expression for simplicity there.

Related

How to examine the contents of data returned from an ajax call

I have an ajax call to a PHP module which returns some HTML. I want to examine this HTML and extract the data from some custom attributes before considering whether to upload the HTML into the DOM.
I can see the data from the network activity as well as via console.log. I want to extract the values for the data-pk attribute and test them before deciding whether to upload the HTML or just bypass it.
$.ajax({
url: "./modules/get_recent.php",
method: "POST",
data: {chat_id:chat_id, chat_name:chat_name, host_id:host_id, host_name:host_name}, // received as a $_POST array
success: function(data)
{
console.log(data);
},
})
and some of the console log data are:
class="the_pks" data-pk="11"
class="the_pks" data-pk="10"
etc.
In the above data I want to extract and 'have a look at' the numbers 11 and 10.
I just do not know how to extract these data-pk values from the returned data from the ajax call. Doing an each on class 'the_pks' does not work as at the time I am looking at the data they have not been loaded into the DOM.
I have searched SO for this but have not come up with an answer.
Any advice will be most appreciated.
I hope I understand your question.
If you get a HTML as a response, you can always create an element and insert that html inside it, without adding it to the DOM. And after that you can search it as you do with a DOM element.
const node = document.createElement("div");
//then you can do
node.appendChild(data);
// or
node.innerHTML = data;
And after that you can search inside the node:
node.querySelectorAll("[data-pk]")
I will re-engineer this - it was probably a clumsy way to try and achieve what I wanted anyway. Thanks to those who tried to help.

Using $.get("url",data) again in jQuery?

I'm attempting to use the $.get() function to get data from a page, and then parse the data through jQuery, such as getting all the images, and then putting it into the body of the user's page.
$.get("/character/hats").done(function(data) {
//$("body").prepend(data);
/*data?*/$(".card > .card-body .col-md-4").each(function(){
let hatdata=$(data).find('pull-left').html;
let hatid=0;
$("body").prepend('<p>found!</p><div>'+hatdata+'</div>');
let assetcode=0;
console.log("I see hat id" + "");
});*/
});
Is there a way to use jQuery data response from $.get, and parse it using jQuery again?
To access the data sent back from $.get you merely need to reference it. You shouldn't convert it back to a jQuery object with $().
Here's an example which gets a JSON response.
$.get('https://httpbin.org/get').done(function(data) {
console.log(data); // data is a variable which contains a parsed JSON response to a javascript object.
console.log(data.url);
});
You can view what the response looks like here: https://httpbin.org/get
If the response of your server isnt JSON you will need to do something else.
If the response is HTML you can do it like this:
$.get('https://httpbin.org').done(function(data) {
console.log(data); // data is now a string of html, which you can insert other places
$('.some-div').html(data);
});
$(...) can be used when you want to 'query' the page's DOM with jQuery. You can query a DOM element with regular Javascript, but it won't include lots of helpful methods like .find() or .html(). So basically you convert an element into a jquery element, which is like javascript on steroids, and adds more methods.
The response from $.get however will either be an object (if its JSON) or a string of html (if HTML). You can convert the string of HTML to jQuery, and parse that as well if that's what you want.
$(data).find('.some-element-in-response')
html() is function not a property name
Change:
let hatdata=$(data).find('pull-left').html;
To:
let hatdata=$(data).find('pull-left').html();
Yes you can I did it but in different way. You need change some way and change few ajax setting like following:
$.ajax({
url: "/character/hats",
type: "GET",
dataType: "html",
success: function (data) {
$(".card > .card-body .col-md-4").each(function(){
let hatdata=$(data).find('pull-left').html;
let hatid=0;
$("body").prepend('<p>found!</p><div>'+hatdata+'</div>');
let assetcode=0;
console.log("I see hat id" + "");
}
});

Convert GET HTML response into document

I am developing a page that reads the source of another page and I need to extract certain information out of that page. I currently have the project snagging the live source with the data however I cannot for the life of me figure out how to convert this string into a document.
My rationale for using a document is that I need to use getElementById etc to get the value of these items.
What have I tried?
Assigning the HTML to an invisible div on my page. This kind of works though it doesn't render the entire HTML string and provides a "shorter" rendition of this page.
Manually finding the substrings. As you can imagine this is a crappy way to do things and provides very unreliable results.
DOM parser to convert the doc and then query it but that fails miserably.
Any assistance at all would be seriously appreciated.
pertinent code:
$.ajax({
method: "GET",
dataType: '',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(res) {
//shows the entire source just fine.
console.log("Value of RES: " + res);
bootbox.hideAll();
//shows a "truncated" copy of the source
alert(res);
$("#hiddendiv").html(x);
var name = document.findElementById("myitem");
alert(name);
},
Create a hidden IFRAME on your document. Then set the contents of that IFRAME to the HTML that you want to query. Target that IFRAME with your javascript when you do your querying. See How can I access iframe elements with Javascript? to understand how.
Another (probably better) option, is to use jQuery. jQuery allows you to create HTML, manipulate it, and query against it in memory. Querying DOM elements in jQuery is even easier than it is in pure javascript. See: http://jquery.com/.
//Get a jQuery object representing your HTML
var $html = $( "<div><span id='label'></span></div>" );
//Query against it
var $label = $html.find( "#label" ); //finds the span with and id of 'label'

How to extract XML tag contents using jquery?

My ASP.NET MVC4 controller returns an XML string, when we pass it a SERIAL. Now when I send a request using C#, it works fine, XML string comes back , and looks like
<CalculatedCode> 12312312 </CalculatedCode>
I need to also do it via jquery like below. Query is working but it is returning an XMLDocumentObject , instead of an xml string. I looked at Jquery documentation to try to parse it, but I'm a jquery noob and I'm sure I'm making an error in the code.
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
dataType: 'xml',
data: { SERIAL: serial}, //SERIAL comes from a textbox
success: function (responseData) {
//Code below is messed up, it simply needs to find the CalculatedCode tag
//and extract the value within this tag
xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
$thecode = $xml.find("CalculatedCode");
// ToDo: Bug stackoverflow members with this noob question
}
});
Thank you very much :)
It's already parsed when you set the dataType to XML, so no need for $.parseXML, but if the element is a root element, find() doesn't work, as it only finds children, you'll need filter()
$xml = $(responseData);
$thecode = $xml.filter("CalculatedCode").text();
an trick that gets the element either way is to append the xml to another element :
$xml = $('<div />').append(responseData);
$thecode = $xml.find("CalculatedCode").text();

jQuery, Ajax and getting a complete html structure back

I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes.
I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like <,>, etc get replaced with the escaped ones
I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean.
I'm sending something like this
<results><table id="test"><tr>test</tr></table></results>
what shows up on my page if I do a page source view is this.
<results><table....
so you can see the special characters are getting converted and I don't know how to stop it.
The idea is for the <results></results> to be the xml tag and the text of that tag to be what gets placed into an existing <div> on my page.
Here is the JavaScript that I'm using to pull down the response and inserts:
$.post(url, params, function(data)
{
$('#queryresultsblock').text(data)
}, "html");
I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the html method of jQuery.
Your result:
<table id="test"><tr>test</tr></table>
Your Javascript call:
$.post(url, params, function(data){ $('#queryresultsblock').html(data) })
Another solution with less control — you can only do a GET request — but simpler is to use load:
$("#queryresultsblock").load(url);
If you must return your result in a results XML tag, you can try adding a jQuery selector to your load call:
$("#queryresultsblock").load(url + " #test");
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go.
One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send
<results><results><table....
And the javascript would convert the < to < and such.
The other option, and what I would do, is to use JSON instead of XML.
{'results': "<table id="test"><tr>test</tr></table>" }
The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
The other thing you could do is create an external .html file with just your HTML code snippet in it. So create include.html with
<results><table id="test"><tr>test</tr></table></results>
As the contents, then use a jquery .load function to get it onto the page. See it in action here.

Categories