So I use a:
$.ajax({
type: "GET",
url: someurl,
success: function(data) {
}
});
If someurl is appropriate, the it returns an XML, if not, it returns a String, which is why I dont specify the dataType parameter.
However, when I get back the XML, it looks like it is in a "Document" object. How do I get within the Document object to store the XML i need in javscript/jquery?
The version of the $ (jquery) operator that works on a selector takes an optional second parameter which is the document on which you want to operate. For instance, $('div', xmlDoc).
Related
I have this JSONP object displayed on a site that generates 3 random numbers. I am trying to access it using the following script embedded in a HTML document.
<script>
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET', //uses GET function
url: url, //stored URL in var
data: {
'callback': 'randomNum'
},
jsonpCallback: 'randomNum',
contentType: 'application/jsonp',
dataType: 'jsonp'
}).done(function(response) {
console.log(randomNum.num1); //ERROR IS HERE randomNum.
});
</script>
The JSONP object looks like this:
Currently I am getting an error. "Can't find variable: randomNum" That tells me that I am not targetting the object correctly.
It is also important to note that the JSONP object does appear in my resources when I hit F12.
Any suggestions on how to target the remote JSONP object?
The issue is in your done() handler. You're attempting to use a variable named randomNum which doesn't exist. Instead you need to use the response variable as passed to the handler function.
Also note that response will be an array, so you need to access the required item by it's index, eg response[0].num1. Try this:
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'randomNum',
dataType: 'jsonp'
}).done(function(response) {
console.dir(response);
console.log(response[0].num1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also note that if your intention is to simply generate a random number then AJAX is huge overkill. You can just use Math.random().
I have some xml data as result of $ajax call.
The question is, how can i get contents (title) of first ?
Thank You for help.
You can use something like
$.ajax({
type: "GET",
url: "you url",
dataType: "xml",
success: function(xml) {
var value = $(xml).find('title').text(); //if only one title node
}
});
Explaination: After getting the response from the url in xml you can simply access the xml response as a Jquery object and use any function of jquery on it.
To access Only the first element use :first selector on it to access the first title element.
eg: var value = $(xml).find('title:first').text();
I have a Javascript application and I need to retrieve an HTML file to template it. The way I am doing this now is:
var _$e = null;
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "xml",
success: function (xml) {
_$e = $(xml.documentElement);
}
});
This does seem to work, but for some reason, I am not getting a proper jQuery object in _$e. I know that because the styling is done by jQuery is getting lost at some point, but also, when I set a breakpoint in success, here is what I see:
> _$e
[<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>]
> _$e.width()
TypeError: Cannot read property 'position' of null
However, when I copy the HTML string manually and convert it to a jQuery object as in success, the output is:
> $('<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>').width()
100
Seems like the xml object returned isn't getting converted properly into jQuery (or not all attributes of the object are being read properly by jQuery -- given that the HTML is rendering but styling isn't).
The xml object is:
> xml
#document
<div class="hello" style="background-color:#FFD700;height:200px;width:100px;">…</div>
Any ideas how to get the xml (or the HTML file) rendered as a jQuery object properly?
Could it be because you're grabbing the datatype XML? Have you tried setting your datatype to HTML (or nothing) and just do this (ignoring the .documentElement and just assuming the whole glomp is your HTML):
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "html",
success: function (data) {
_$e = $(data); // we are getting back HTML,
console.log(_$e.width()); // jQuery is fine with html globs
}
});
This is likely because you are pulling it in as XML. Try setting the dataType to html and see if that makes any difference.
It also sounds like .load() might better fit your needs: http://api.jquery.com/load/
Is there a name for a pre-loaded AJAX object stored in memory?
If I wanted to use this code:
function GetXML() {
$.ajax({
type: "GET",
url: "questions.xml",
dataType: "xml",
success: function(xml) {
} //close success
});//close AJAX
}; //close function GetXML
to load some XML, how would I store this data on an object? Would I have to create a new variable on the object to store this XML? That's what I've found. If so, what would the type would the variable be? (e.g. String, Int, something of that nature)
Would it be 'Object XML' or something of that sort?
Thanks, Elliot Bonneville
Since you are setting dataType: 'xml' in the AJAX request, jQuery will parse the response into an XMLDocument object.
Note that there are certain circumstances where you will need to do this manually. (Related to an IE bug, of course)
You'll have to use a JavaScript XML parser to convert it to an object. There are a lot of pre-made ones, but if you want it for something simple check: http://www.w3schools.com/Xml/xml_parser.asp
Since you're using jQuery already, parse the data like you parse the elements of an html document with regular $() calls on elements in the xml.
you could use jQuery('example
I have tried and failed to find out how to get the entire XML string from the XMLDocument returned by a GET. There are a lot of questions on SO on how to find or replace specific elements in the object, but I can't seem to find any answer to how to get the entire document as a string.
The example I'm working with is from here. The "do something with xml"-part is where I'm at at the moment. I get the feeling that this should be really trivial, but I fail to find out how. Is there an "xml.data()" or similar that can be used for this purpose?
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
The use case is that I want to feed the xml to flash plugin and for that I need the actual XML as a string.
If you want both, get the response as XML Document and as string. You should be able to do
success: function(data){
//data.xml check for IE
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
alert(xmlstr);
}
If you want it as string why do you specify dataType:xml wouldn't then dataType:text be more appropriate?
I need the actual XML as a string
You want it as plain text instead of XML object? Change dataType from 'xml' to 'text'. See the $.ajax documentation for more options.
You can also easily convert an xml object to a string, in your java script:
var xmlString = (new XMLSerializer()).serializeToString(xml);
If you only need a string representing the xml returned from jquery, just set your datatype to "text" rather than trying to parse the xml back into text. The following should just give you raw text back from your ajax call:
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'text',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
Although this question has already been answered, I wanted to point out a caveat: When retrieving XML using jQuery with Internet Explorer, you MUST specify content-type to be "text/xml" (or "application/xml") or else you will not be able to parse the data as if it were XML using jQuery.
You may be thinking that this is an obvious thing but it caught me when using Mozilla/Chrome/Opera instead of IE. When retrieving a "string" of XML with a content-type of "text", all browsers except IE will still allow you to parse that data (using jQuery selectors) as if it were XML. IE will not throw an error and will simply not return any results to a jQuery selection statement.
So, in your example, as long as you only need the string-serialized version of the XML and will not expect jQuery to do any sort of selection on the XML DOM, you can set the content-type to "text". But if you ALSO need to parse the XML with jQuery, you will need to write a custom routine that serializes the XML into a string for you, or else retrieve a version of the XML with content-type "xml".
Hope that helps someone :)
You can get the native XMLHttpRequest object used in the request.
At the time i'm posting this answer, jQuery docs state a few ways to do so.
One of them is via the third argument of the success callback:
success: function(xml, status, xhr){
console.log(arguments);
console.log(xhr.responseXML, xhr.responseText);
console.log('Finished!');
}
For a complete example:
https://jsfiddle.net/44m09r2z/