How to Extract HTML from Content Fetched with Ajax using jQuery - javascript

I have a page, in which there are a couple of Option elements whose Value point to external pages. My aim is to use Ajax to extract the chosen Option's Value & use that to load content from external pages. E.g. When a user chooses Volleyball, I will get the 'volleyball.html' value, use Ajax to retrieve that page and load its #catalog content into the current page. Here's my code:
$("select").change(function(){
var selectedURL=$("option:selected",this).val();
if(selectedURL!=="Select One"){
$("#center").html("<p class='processing'></p>");
$.get(selectedURL,function(data){
var extractedContent=$("#catalog",data);
console.log(extractedContent); //Firebug says extractedContent is '[]'
$("#center").html(extractedContent); //Nothing is inserted inside div#content
},"html");
}
I'm not good at jQuery, and have kind of mixed and matched code from a few posts here to derive at the above. Now I'm not sure what went wrong, but nothing is loaded - the #center div block that is supposed to hold the extracted content is empty.
Can someone please help me spot just what's wrong with my code above? Many thanks in advance.

The load() method is perfect for this:
$('select').change(function () {
var selectedURL = $('option:selected', this).val();
if (selectedURL !== 'Select One') {
$('#center').html('<p class="processing"></p>').load(selectedURL + ' #catalog');
}
});
It can take only a URL, or it can take a URL followed by a selector which will only load the contents of the matched element (#catalog) into the element it is called on (#center).

You can't use $('#catalog', data) just like that. To extract content, you can create a jQuery object, and assign the HTML returned then extract from there:
var extractedContent = $('<div />').html(data).find('#catalog').html();
console.log(extractedContent);
$("#center").html(extractedContent);

$("select").change(function(){
var selectedURL=$("option:selected",this).val();
if(selectedURL!=="Select One"){
$("#center").html("<p class='processing'></p>");
$.get(selectedURL,function(data){
$("#center").html($(data).find("#catalog"));
},"html");
}
});

Related

Get only a paragraph from http response [duplicate]

I'm looking for a way to get a HTML element from a string that contains HTML. Is it possible to use a jQuery selector to do this?
I have a Javascript function that gets an entire page from the server, but I only need one element from that page.
Yes, you can turn the string into elements, and select elements from it. Example:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);
Just wrap the html text in the $ function. Like
$("<div>I want this element</div>")
If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()
$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');
For example:
$('#result').load('ajax/test.html #container');
Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.
Just use $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")
You can use $.find
$(document).ready(function() {
var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
var spanElement = $(htmlVal).find("span");
var spanVal = spanElement.text();
alert(spanVal);
});

Load html file - and access element ID's

I have loaded a html file and "placed" it inside a div:
document.getElementById('my_div').innerHTML='<object type="text/html" data="table.html" ></object>';
Works fine, but when I try to get an element by it's ID in the table (from table.html) I get null/undefined.
var table = document.getElementById('my_table'); /* Nope! */
I guess I am doing it at the wrong time or place somehow. Can you help me please?
Best Regards
I would do this with jQuery's built-in AJAX method, .load(). Like so:
$(document).ready(function(){
$('#my_div_id').load('/filepath/table.html');
var table = $('#my_table');
// Other code, presumably :)
});

Getting element by tag name after getting a page using jQuery $.get

I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.

jQuery load issue. Don't know how to approach this AJAX call

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

Categories