Trouble getting XML data to show on HTML using jQuery - javascript

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

Related

AJAX isn't loading the other js and css style

I wrote a short AJAX code which is getting Facebook contents from a PHP file (in the PHP file I have declared class="gallery-img-link" as <a> and class="img-responsive img-thumbnail" as <img>).
I have the gallery-img-link on the bottom of site as jQuery script, the problem is when I add those classes by hand its working fine, but when I try to load those by a AJAX get request it seems to doesn't work.
Should I use it in a document.ready function?
I have tried live as well, but that didn't helped at all.
$(document).ready(function(){
$(\'#loading-image\').show();
$.ajax({
method:\'get\',
url:\'ajax.php\',
success:function(data){
$("#facebook").html(data);
},
complete: function(){
$(\'#loading-image\').hide();
}
});
});
For all JavaScript DOM manipulations you Need the DOM to be fully loaded.
Without having your PHP and other Code around I can just correct your JS:
$(document).ready(function(){
$('#loading-image').show();
$.ajax({
method: get ,
url: ajax.php ,
success: function(data){
$("#facebook").html(data);
},
complete: function(){
$('#loading-image').hide();
}
});
});
UPDATE:
Go Into the f12 Developer Tools in your Browser, and go to the Network Tab, then have a llok o all loaded Files, on should be ajax.php. Have a look what the File of that COntent is
Basicly the problem was that the content has been loaded but the "photo java script file" wasnt waiting to get the page loaded, so this function couldnt work at all. Becasue those AJAX loaded after "reading JS function".

Why does my JS/JQuery code only work in a web browser's console?

The $(element).scroll(function(){}); function isn't working for me when I put it into a js file but when I enter it into the console (just the scroll func), it works just fine.
I'm trying to do a scrolling pagination.
I've looked through my other js files and the only thing that I think could be conflicting is another one of the files has a $(document).ready(function(){}) but I'm pretty sure that's not the problem. I'm also using Dropkick to make pretty dropdowns but I doubt that's it either.
Here's the code, almost verbatim. It's basic for now until I can figure out how to get it to load.
$('#main').scroll(function(){
if(($('#main').prop('scrollHeight'))==
($('#main').scrollTop()+$(document).height()-10)){
//^there's a strange 10px empty space that needs to be accounted for
$('#loading').show();
$('#main').css('overflow','hidden');
addMore();
}
});
$(document).ready(function(){
addMore();
});
addmore.counter=0;
function addMore(){
$.ajax({
async: 'true',
url: 'http://mywebsite.com/bc/get',
type: 'post',
data: ({'offset':(addmore.counter)}),
success: function(data) {
$('#scrollingpagination').append(data);
$('#loading').hide();
$('#main').css('overflow','scroll');
addmore.counter++;
}
});
}
And here's the HTML (not verbatim, but same idea)
<!--I'm only including the "main" div that shows the content.-->
<div id='main'>
<div id='scrollingpagination'></div>
<div id='loading'></div>
</div>
Thanks guys, I really appreciate it!
try keeping
$('#main').scroll(function(){
......
})
inside document.ready. i think it was called before the dom was ready

JQuery dynamic Script-Tag and the Execution

The goal is to load script-Tags per ajax, execute the scripts and show the content of the script-tag (a iframe with a video).
The scenario:
The scenario is a video page. If i click on "video-text" the id in the dom will be determined. After that an ajax-php-request will be executed with the determined id. This request will responese with a script tag. And this is the problem: How can i get the iframe?
Have anyone a tip for me?
ajax-call:
$.ajax({
type: "GET",
url: "/get-embed-by-id/"+$(this).find('.views-field-nid .field-content').html(),
success: postToPageTwo,
error : postToPageTwo,
datataype: "html",
});
This call returns a script like this one
<script type="text/javascript" src="http://exampleurl.de/video/7"></script>
The content of this script is for example:
(function(){
document.write('<iframe id="video_11" class="mediacube_video"
src="http://exampleurl.de/video/11.html?" scrolling="no"
align="center" frameborder="0" framespacing="0" width="725" height="409">
</iframe>');
})()
EDIT
the code to use with $.getScript:
$.getScript("http://exampleurl.de/video/5", scriptResponse);
and the code of scriptResponse:
function scriptResponse(data) {
console.log("data:");
console.log(data);
}
but the data is always undefined. or did i anything wrong?
jQuery has .getScript() to load and execute scripts for you. no need to call an ajax to return an html to load another script (that's a lot of round trips) just to call a script.
$.getScript('http://exampleurl.de/video/7');
if the initial request really matters (maybe some parsing on the back-end to determine the link of the script), you can have the initial response return just the url of the script. then use that returned string for the .getScript()
$.get('initial_url',function(returned_url){
$.getScript(returned_url);
});
but still, too many round trips.

<script> tags getting stripped from output

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.

null body issue with AJAX call

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

Categories