Is there a name for a pre-loaded AJAX object? - javascript

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

Related

Serialize and de-serialize array (without jquery?)

I have a method which sends an ajax request. When the reply from the server is received I need to serialize and later de-serialize
$.ajax({
//.....
done(function(data) {
//1 Need to serialize data (which is an array)
});
function myFunction() {
//2 Need to de-serialize data which has been serialized
}
I know I could use jquery#serializeArray() if I had a form to serialize:
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
But I don't have a form and data from the server (I guess) has nothing to do with serializeArray function of jquery. So how can I do it? What's one of the best ways?
Preferably not to use any third-party libraries except jquery or even not to use jquery at all.
The common way to serialize JS-objects to JSON is via JSON.stringify().
The other way around is via JSON.parse().
o={"firstName":"john","lastName":"doe"};
console.log(JSON.stringify(o));
console.log(JSON.parse(JSON.stringify(o)));
See MDN for stringify and parse
Here is a Fiddle.
.serializeArray() from jQuery is only a neat helper function to serialize form-data.
It builds its objects from the ground up. Here is the source for that.
If you want to submit your data as JSON, you simply
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: success,
dataType: dataType
});
Free after jQuery.post().

easyXDM form post

I'm in the process of converting my jquery ajax calls to use easyXDM. How might I go about doing something like this:
xhr.request({
url: "someurl",
method: "POST",
data: $("#formid").serialize(), // serializes the form's elements
}, function(rpcdata){
// do stuff
});
My issue is with serializing the form's content. It appears that easyXDM is expecting json. Is there a simple way to convert my form to json? Or is there a way to tell easyXDM to use a standard query string?
Here's one solution:
http://css-tricks.com/snippets/jquery/serialize-form-to-json/

Convert Document Object to XML Document JQuery?

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).

Return String from Cross-domain AJAX Request

I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});

How do I get the entire XML string from a XMLDocument returned by jQuery (cross browser)?

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/

Categories