Select a node with namespace in jQuery - javascript

I'm using YQL to fetch data using JSONP, and it returns a string of XML. I parse it using $.parseXML and put it inside the jQuery selector and try to select a node. However, it contains a namespace (for example, yweather:) and jQuery seems to not working as it should be.
From other SO answers they suggested that doing \\: will solve it. It does, but only when the data I received is XML (mine is with JSONP.)
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
data: {
q: "select item from weather.forecast where location=48907",
format: "jsonp"
},
dataType: "jsonp"
}).success(function(data){
var xml = $.parseXML(data.results[0]);
console.log($("yweather\\:condition", xml));
});
It didn't match anything.

Could not figure out why it is not working, also other answers suggested escaping : with \\. But it is not working. So I have tried in this way and it is working. This is also equal to jQuery's find method and it is working demo
Code is
var xml = $.parseXML(data.results[0]);
xml = $(xml).find('channel item');
var weatherList = xml.find('*').filter(function(){
return this.tagName === "yweather:condition";
});
console.log(weatherList);
Hope this helps.

Related

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" + "");
}
});

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();

$.get with dynamic data names?

I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});

Update link text with content from XML document

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.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories