jquery html returns null - javascript

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

Related

How to embed HTML <tag> that is returned in JSON

In short:
The response to an AJAX call returns 2 HTML elements, script and div, which are stored in JSON format. The response is structured like this:
Object { script : "<script>...</script>", div : "<div></div>" }
response contains the objects in JSON that I need to embed. How can I do this? My code:
<body>
<script type=text/javascript>
$.ajax({
url: "my.url",
type: "GET",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(response){
// Code that embeds script and div in to the body of the document
}
});
</script>
A bit more detail:
div contains 3 graphs that are referenced from the script element. Both of them are returned from a python script that runs bokeh. Everything else works fine, I am just new to HTML and javascript and that is why I don't know how to embed the tags from the JSON to the html body.
Thank you for your help!
EDIT: Unlike here, I am asking specific help on how to embed the returned JSON without any div parameters to AJAX function
You have to parse your JSON to an object via the JSON.parse() function
<body>
<script type=text/javascript>
$.ajax({
url: "my.url",
type: "GET",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(response){
// Parse to object
var object_response = JSON.parse(response);
// Access object like this
var response_script = object_response.script;
// And the second one the same way
var response_div = object_response.div;
// And then, for example, you can then append that div like this
$("body").append(response_div);
}
});
</script>
Edit changed -> to . as suggested below
Second edit, it's true that you won't need JSON.parse() under 1 condition, is that you set your headers right header('Content-type:application/json'); otherwise this technique as suggested in the comments will not work and you will have to use JSON.parse() function
Use "jQuery.parseHTML()" to parse your string to a valid DOM Element. After this, you can use the ".append()" function to add it to your body.
Use $("html body").append( to add javascript in body after page load
function oldDivClicked(){
console.log("old Div Clicked");
}
function changeDiv(){
$("#mydiv").html('<span onclick="newDivClicked()">New Div: apply newDivClicked()</span>');
$("html body").append('<script>function newDivClicked(){console.log("new Div Clicked");}<\/script>');
}
<div id="body">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"><span onclick="oldDivClicked()">Old Div: apply oldDivClicked() </span></div>
<button onclick="changeDiv()">Get New Data</button>
</div>
When page load newDivClicked() is not present and when you click on Get New Data you will also be able to get newDivClicked().
Example of dynamic script and div include:
var data = {
script: "<script type='text\/javascript' >alert('It works')<\/script>",
div: "<div class='info'>info<\/div>"
};
$('body').append(data.div);
$('head').append(data.script);
My fiddle: https://jsfiddle.net/8um4qe8h/1/
P.S. I needed to put escape char to run this example, so that's why data looks ugly

Jquery, retrieving data from externel url and parsing result

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

Retrieving HTML file using AJAX

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/

How to get the html of a div from a different page with AJAX?

How can I get the html of a certain html element which is located on a different site?
Solution:
$.ajax({
url: 'somefile.html',
success: function(data) {
data=$(data).find('div#id');
$('#mydiv').html(data);
alert('Done.');
}
});
You can use $.load with an appended container
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted.
$('#result').load('ajax/test.html #container');
Make a ajax call to a php or any other file , use CURL or other tools to grab the page you want and extract the div and echo it and then when you get back the html just put it inside a div in your page
$.ajax({
url: 'somefile.html',
success: function(data) {
data=$(data).find('div#id');
$('#mydiv').html(data);
alert('Done.');
}
});
Here you go:
$('#div_id_in_your_page').load('ajax_page.html #required_div');
For class:
$('.div_class_in_your_page').load('ajax_page.html #required_div');
One way is:
send an ajax call to a server side script
this script fetches the remote page and returns HTML as a response. (generally JSON is preferred)
your page finally gets access to the html.
you can also use like this.
$.ajax({
url:"page2.html",
success:function(response){
$("#currentDIV").html(response);
},error:function(){
alert("error");
}
});

Assign entire file to a var as a string using jquery

I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}

Categories