Retrieving HTML file using AJAX - javascript

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/

Related

Extract object from JS script loaded with synchronous jQuery ajax call

I am trying to get use an object from a script loaded synchronously using Ajax via jQuery.
From this script I am trying to load an object which looks like this from a script called map_dropdowns.js which returns the object options:
{curr_cat: "RELATIONSHIP"
curr_subcat: " Population in households"
curr_total: "Total"}
My code for the script with the ajax is here:
<script>
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "script",
async: false,
success: function(data){
console.log(data);
}
});
console.log(options); //returns `Object{}` in the console, and only shows values when expanded
options["curr_cat"]; //returns undefined
console.log(Object.keys(options)); //returns an empty array []
</script>
In the original script, the keys and values within options can be accessed perfectly fine. console.log in Chrome shows its contents fully without needing to be expanded (Object {curr_cat: "RELATIONSHIP", curr_subcat: " Population in households", curr_total: "Total"}), and Object.keys() works just fine.
After it is loaded onto the page with the Ajax function, however, trying to access the values using the keys comes up undefined, Object.keys turns up an empty array [], and the key:value pairs are only shown in the console when I click on the object, with it otherwise showing only Object {}.
I am pretty sure that I need to do something in the success function of the Ajax, but I am not sure what after a lot of trial and error.
Thanks!
Loading JS code via AJAX is always a little hit and miss. It's usually a much better idea to load the data either as HTML, XML or JSON, and then deal with it as required once the AJAX request completes.
In your case, as you're attempting to load an object, JSON would be the most appropriate. If you change your map_dropdowns.js file to return data in this format:
'{"curr_cat":"RELATIONSHIP","curr_subcat":"Population in households","curr_total":"Total"}'
You can then make your async request to get this information from this file:
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "json",
success: function(data){
console.log(data.curr_cat); // = 'RELATIONSHIP'
console.log(data.curr_subcat); // = 'Population in households'
console.log(data.curr_total); // = 'Total'
}
});

Ajax loading image error

my question is very simple. I have drafted the code as follow for showing the loading image when the form is being posted. The loading image can be shown properly. However, it cannot hide automatically after the result is returned. May i know what is the error?
HTML
<div id="loading"></div>
Ajax
function email_subscribe(){
$('#loading').html('<img src="loading.gif"> loading...');
$.ajax({
type: 'post',
url: 'index.php?subscribe',
dataType: 'html',
data:$("#subscribe").serialize(),
success: function (html) {
$('#loading').html();
eval(html);
}});
}
You're just calling the .html() method without any parameters (which serves as a getter). To achieve what you're looking for here, you need to at least pass in like an empty string to set and overwrite existing content.
$('#loading').html('');
I also think you should not use eval....
...and yes call .html() with an argument like:
$('#loading').html(" ");
or
$('#loading').html(" ");

jquery html returns null

I am trying to download a webpage and extract the body.
Given I have the following code:
$.ajax({
url: someAccessiblePublicUrlOnSameWebServer,
dataType: 'html',
success: function (data) {
//data is correct at this point
var body = $(data).find('body').html();
//body is null. why ?
}
});
success is called and data contains the expected html but body is always null. Why ?
$.ajax({
url: someAccessiblePublicUrl,
dataType: 'html',
success: function (data) {
var body = $(data).find('body').html();
}
});
It may be that you have a typo in there.
Did you mean:
var body = $(data).find('body').html();
Note the single ticks around body.
If you load HTML via Ajax call it will always return data as a string so you will be unable to apply normal jQuery selectors to a response. If you convert the data to $(data) you will also not be able to access body as $(data) is a collection of the contents of the body (stripped by jQuery internal clean() method). You have a few options depending on what you want to do with the result:
If you want to just append the body of the loaded html somewhere in the document you can do this:
$.get('http://your_url', function(data) {
$('.result').html(data);
});
This will load just the body contents to the .result container. If you want to do any further processing you can access the selectors from there.
If you just want to manipulate the unattached fragment you can access it's elements by using filter & get.
$(data).filter('p').get() //will get all para DOM nodes
$($(data).filter("#test2").get()).text() //will get text of one specific dom node
Another option if you want to process the data in the body it might be faster to process it as XML - for XML processing look at http://think2loud.com/224-reading-xml-with-jquery/.
Using your example it would be something like that:
$.ajax({
url : "http://mypage",
dataType : 'xml', //change dataType to XML
success : function(data) {
//data is correct at this point
$(data).find('html').each(function() {
//here you can find whatever you want
a = $(this).find("body")
console.log(a);
})
}
})
Unless it was a typo, you need quotes around the "body" inside your find method.
IE: var body = $(data).find('body').html();
That could be your problem.
Correction to my last response.
Check out this thread parse html string with jquery
Using that, I think this will work
var body = $("body", $(data)).html();

Get jQuery object from HTML string

I have an AJAX request that grabs the source of Wikipedia pages:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
success: function (html) {
var page = $(html);
alert(page.find("#content").length); //Alerts 0
alert(page.html()); //alerts null
}
});
It successfully returns the source of the page (I have a copy of the string it returns here on jsFiddle).
The problem: I can't seem to make a jQuery object from the HTML (like they do here). For some reason, it doesn't seem to be creating the object correctly. What am I doing wrong?
html data seems to be badly parsed (maybe a closing div tag is missing in the html code), use:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
datatype: "html",
success: function (html) {
html=html.replace(/(<body [^>]*>)/i, '$1<div>').replace(/(<\/body>)/i, '</div>$1');
var page = $(html);
alert($("#content",page).length); //Alerts 1
alert(page.html()); //alerts html
}
});
html string contains the links pointing to en.wikipedia.org site, so when we do $(html) jQuery might be getting exception due to cross domain script calls inside the html markup due to which you are not getting any thing after $(html)

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