when i try to do an AJAX call to get some html text, i get a null body file. (Context is i am trying to do a hybrid application on Android and used weinre to check what i have received from the AJAX call)
The AJAX call is within the following code:
$(document).ready(function(){
$("#generate").click(function(){
$.ajax ({
cache: false,
url: "htmlpage1.html",
success: function(html) {
console.log(html);
$("#quote p").append(html);
}
});
});
and the htmlpage1.html is the following
<body>
This is page1
<p><b>And this is some text which has been bolded</b></p>
<p>And this is the link to page 2
</body>
did some research on stackoverflow and tried by luck with the following 'magical' line to the ajax code, the problem is somehow fixed
if(null==document.body){document.body = $('body')[0];}
what is the reason i get this issue in the first instance and how this problem is fixed by this code
if i dont use the magical code line but instead insert a dummy tag in the html_page1 file, i manage to get the html file via AJAX (i.e. null body tag is fixed. )
You could also try to find the body tag before appending it, it might give you the content you need... try playing with the selectors, I had a similar issue before.
$("#quote p").append($(html).find("body"));
Related
I'm working on my new PC builds website and I have trouble getting XML tag with specific attribute to show up in my HTML <p> element. My XML looks like this:
<?xml version="2016.6" encoding="UTF-8"?>
<parts>
...
<HDDs>
<hdd id="1">
<name>DiskOne</name>
<price>50</price>
</hdd>
<hdd id="2">
<name>DiskTwo</name>
<price>40</price>
</hdd>
</HDDs>
...
</parts>
I want to find tag <hdd> with attribute id="2" in above XML and show its child's name content in HTML <p> element, which has the id="test-xml". I used this jQuery code to get data from XML and show that in <p>:
function loadHDDs(name)
{
$.ajax({
type: "GET",
url: 'data/parts.xml',
dataType: "xml",
success: parseHDDsXml
});
}
function parseHDDsXml(xml, name)
{
$(xml).find('hdd[id="2"]').each(function(){
var name;
name = $(this).children('name').text();
$("#test-xml").text(name);
});
}
I found the code in another website and I don't really know, what do I need to write in brackets after loadHDDs, so I wrote name. I don't know how to cleanly make the script execute when the page is loaded, so I added onload="loadHDDs();" to the <body> element on my page. I use Google Chrome debugger to find errors. When I tested my page locally, on my computer, debugger, of course showed that XMLHttpRequest cannot load. I uploaded my project to the server and I receive no errors in the Chrome debugger at all, but the text in <p> element doesn't change to the XML text. What am I doing wrong? Maybe something is wrong with my script? Or XML document? Maybe I just don't know to execute jQuery script and onload just doesn't work? Please, help me! I'm a beginner in jQuery and Javascript, so I kindly ask you to show me the easiest and most understandable way of fixing the problem.
Thanks in advance!
EDIT: I don't have enough reputation to comment. I added error function to my Ajax as Nayeri suggested and now I get an error that loadHDDs is not defined. I don't understand that. We can clearly see function loadHDDs(name) in my script. I have checked the spelling a hundred times.
Add error function to your ajax to see your errors :
$.ajax({
type: "GET",
url: 'data/parts.xml',
dataType: "xml",
success: parseHDDsXml,
error : function (a,b,c){
console.log(a, b, c)
}
});
then your xml file seems is wrong so Remove the <?xml version="2016.6" encoding="UTF-8"?> line of your xml file
Im trying to do something that should be very simple yet my head is about to explode considering I cannot get it to work.
In my asp.net MVC app, I make an Ajax call to the server, and the server sends back a message (as a string), which includes a link.
The message basically looks like this : Action failed, Learn more..
I am inserting this returned message in a div that shows the alerts from the server.
However, whatever I try, the 'Learn more.' part will never be inserted.
If I do alert(returnedMessage), it shows the correct html, but as soon as I do
$(mydiv).html(returnedMessage), the anchor-tag is gone. I tried unescaping, normal jscript innerHtml...not sure what I'm missing.
Thanks!
**UPDATE with some extra code **
I have the ajax call that returns a message. I have a method that then sets the message into the div and shows the alert.
the ajax call handling:
success: function (result) {
if (result.Message) {
showAlert(result.Message);
}
},
The javascript:
function showAlert(message) {
// neither setting the actual div, nor the span works
alert(message);
$('#server-message').html(message)
//$('#server-message span').html(message);
$('#server-message').fadeIn(100);
};
the html:
<div id="server-message">
<span></span>
</div>
also worth trying if you are escaping the double quotes properly :)
var returnMessage = 'Learn more.';
You should your message to .html() function $(mydiv).html(returnedMessage) if you doing $(mydiv).html = you only overwriting html property in this object.
I have an application that builds page content from multiple page fragments comprising the template page. One or more of these fragments need to run JavaScript when the document has loaded, and it does not make sense to put fragment specific code in the template page comprising the fragments. While this approach has worked out for me quite well, I have a problem when attempting to update a fragment via Ajax based on the user's interaction with the page.
I am using jQuery and $(document).ready(function() {...}); rather liberally, both in the template page (for globally scoped code) and the fragments (for fragment specific code). Problem is, when a fragment is updated using jQuery's .html(HTML code from Ajax response) on the jQuery enriched version of the HTML element and the Ajax response itself contains $(document).ready(function() {...}); code, the HTML content gets updated nicely but the JS does not execute.
Some suggest use of eval() on the JS fragments inside the Ajax response while others forbid it. I am hoping someone will push me in the right direction with this.
$.ajax({
type: 'POST',
url: $(formObj).attr('action'),
data: $(formObj).serialize(),
})
.done(function(data, textStatus, jqXHR) {
$response = $(data.replace(/<body(.*?)>/,'<body$1><div id="ajaxResBody">').replace('</body>','</div></body>'));
$('#fragmentContent').html($response.find('#fragmentContent').html());
});
<div id="fragmentContent">...</div> is one of the fragments updated using partial content extracted from the Ajax response. When the page is initially loaded, the fragment's content DOM looks approximately like this:
<div id="fragmentContent">
<p>...</p>
<div>...</div>
<script type="text/javascript">
$(document).ready(function() {
// JS code
});
</script>
</div>
But when the same fragment's content is replaced via Ajax, the DOM looks like this:
<div id="fragmentContent">
<p>...</p>
<div>...</div>
</div>
So it is quite apparent scripts are stripped. I verified that by using the following code:
if (data.indexOf('accordion(') >= 0) {
console.log('scripts found in Ajax response');
if ($response.find('#fragmentContent').html().indexOf('accordion(') >= 0) {
console.log('scripts inserted into fragment');
}
else {
console.log('scripts stripped before content inserted into fragment!');
}
}
else {
console.log('scripts did not even make it in the Ajax response!');
}
and the following log output was yielded:
scripts found in Ajax response
scripts stripped before content inserted into fragment!
i am working on a single page application using jQuery. whole html pages are sent as response to browser as ajax response.
$.post(url, function (data) {
$("#resp").html(data);
$("#resp").find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
how to remove script tags from data and than assign html to the div ?
the issue i am facing is the scripts that are written in the response page. they were not getting added to the DOM at first, so i used eval(), now the scripts are getting added twice in some situations.
The easiest way would be to use the .load() function with a fragment selector, since that will strip out <script> tags prior to updating content and result in them not being executed. If you're working with entire HTML pages though there may not be a suitable selector for you to use. However, I'd suggest trying this first:
$('#resp').load(url + ' body');
That would give you just the content between the <body> and </body> tags in the HTML page requested via AJAX.
If that doesn't work, I guess you could try manually stripping out <script> tags from the response prior to adding to the DOM:
$.post(url, function(data) {
var tempDiv = $('<div>').html(data).find('script').remove();
$('#resp').html(tempDiv.html());
});
That creates a new <div> element that isn't part of the document, sets its HTML to the returned HTML from the AJAX request, searches for <script> elements inside that, and then removes them. However, even though the element isn't part of the current document yet, the scripts may still end up being executed (I've never had a reason to do this so I haven't tested it).
with the help of Anthony's answer this is what i did to get it working :
$.post(url, function (data) {
var tempDiv = $('<div>').html(data);
var raw = $('<div>').html(data);
$(tempDiv).find("script").remove();
$("#resp").html(tempDiv.html());
$(scripts).find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
i could not understand why
var tempDiv = $('<div>').html(data).find('script').remove();
did'nt work though.
I am building a tumblr theme and have an ajax call that gets a video player, the video player code is returned and I log it out to the console (see #1). I write out the returned html to an element (#2) and then write out the contents of that element (#3) and the tags get parsed out.
Can anyone help me understand why the script tags are getting stripped and how I would get the script to run please?
console.log(data.posts[0]["video-player"]); //#1
$("#DOMWindow .post-inner .video-container").html(data.posts[0]["video-player"]); //#2
$("#DOMWindow .post-inner .video-container").html(); //#3
Below is the output in the console for data.posts[0]["video-player"]
<span id="video_player_21019988413">[Flash 10 is required to watch video.]</span><script type="text/javascript">renderVideo("video_player_21019988413",'http://penguinenglishlibrary.tumblr.com/video_file/21019988413/tumblr_m2f2kbQFzu1rsq78z',400,225,'poster=http%3A%2F%2Fmedia.tumblr.com%2Ftumblr_m2f2kbQFzu1rsq78z_r1_frame1.jpg,http%3A%2F%2Fmedia.tumblr.com%2Ftumblr_m2f2kbQFzu1rsq78z_r1_frame2.jpg,http%3A%2F%2Fmedia.tumblr.com%2Ftumblr_m2f2kbQFzu1rsq78z_r1_frame3.jpg,http%3A%2F%2Fmedia.tumblr.com%2Ftumblr_m2f2kbQFzu1rsq78z_r1_frame4.jpg,http%3A%2F%2Fmedia.tumblr.com%2Ftumblr_m2f2kbQFzu1rsq78z_r1_frame5.jpg')</script>
Below is the output from the .html() call with the elements stripped #3
<span id="video_player_21019988413">[Flash 10 is required to watch video.]</span>"
Below is the full ajax call that should be inserting the script tags into the page but doesn't:
$.ajax({
url: 'http://penguinenglishlibrary.tumblr.com/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
var videoPlayer = data.posts[0]["video-player"];
$("#DOMWindow").find(".post-inner .video-container").html(videoPlayer);
}
});
The jQuery .load() function always strips out <script> tags, and on top of that when you use the "context" variation as you are it does not execute them.
That is,
$('#foo').load('http://what.ever.com/stuff .something', function() { /* ... */ });
That ".something" suffix after the URL triggers this weird "feature".
I logged a bug about this and the resolution was a documentation update. For various internal reasons it'd be pretty hard to make it work better.
edit — there's really no direct workaround other than to have your server do the work of separating out the page fragment you need. jQuery just won't cooperate, mostly (I think) because the library would have to somehow figure out what scripts from elsewhere in the retrieved page needed to be run.
Pointy said
For various internal reasons it'd be pretty hard to make it work better.
The internal reasons are that assigning to a DOM node's innerHTML property does not execute script element's content.
Can scripts be inserted with innerHTML? explains.