By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,230 Members | 2,427 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,230 IT Pros & Developers. It's quick & easy.

XMLHttpRequest to fetch a specific div

P: n/a
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

I was going to use Ajax on mouseover but keep the normal link intact,
so that if the user does not have javascript they can click the link
as normal and this would take them to the new page, but if they have
javascript (and ActiveX enabled I guess, in the case of IE) it would
just fetch the appropriate div into the current page. This would save
having to duplicate content so that it can be served by Ajax.

Of course, changing content on mouseover could annoy many users... is
there a way to change a link location using DOM on page load, as you
might a class name?

eg an onload function changes <li id="product1"><a
href="product1.html".... to <li id="product1"><a href="#", so that the
XMLHttpRequest can be moved to an onlick event--but if there is no
javascript present, the hard link would remain intact.

thanks for any pointers!

Feb 20 '07 #1
Share this Question
Share on Google+
17 Replies


P: n/a
br*******@gmail.com said the following on 2/20/2007 6:03 AM:
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?
No.
I was going to use Ajax on mouseover but keep the normal link intact,
so that if the user does not have javascript they can click the link
as normal and this would take them to the new page, but if they have
javascript (and ActiveX enabled I guess, in the case of IE) it would
just fetch the appropriate div into the current page. This would save
having to duplicate content so that it can be served by Ajax.
I love it when people want to use "Ajax" so they can say "we use Ajax".
Of course, changing content on mouseover could annoy many users... is
there a way to change a link location using DOM on page load, as you
might a class name?
Yes, but why?
eg an onload function changes <li id="product1"><a
href="product1.html".... to <li id="product1"><a href="#", so that the
XMLHttpRequest can be moved to an onlick event--but if there is no
javascript present, the hard link would remain intact.
That is one crazy idea you have there. Why not:

<a href="product1.html" onclick="someAJAXFunction();return
false">Product</a>

End of problem.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 20 '07 #2

P: n/a
modified some existing code... think it's nearly there, but where am I
falling down?

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(fetchdiv, targetdiv)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetdiv);
XMLHttpRequestObject.open("GET", fetchdiv);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML =
XMLHttpRequestObject.responseXML.getElementById('d iv2')

}
}

XMLHttpRequestObject.send(null);
}
}

Feb 20 '07 #3

P: n/a
On 20 Feb, 06:10, Randy Webb <HikksNotAtH...@aol.comwrote:
brough...@gmail.com said the following on 2/20/2007 6:03 AM:
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

No.
It appears to be possible to process an XML file fetched using
XMLHttpRequest and extract specific data, so I think this should be
able to be applied to a html document in order to extract the contents
of one div.

That is one crazy idea you have there. Why not:

<a href="product1.html" onclick="someAJAXFunction();return
false">Product</a>

End of problem.
Ah ha! So it doesn't follow the link.

How do you add return false to mouse events that are in an external
script? eg:

var nav = document.getElementById('test').getElementsByTagNa me('a');
for (var i=0;i<nav.length;i++)
{
nav[i].onmousedown = someAJAXFunction;
}

I've had a play but "someAJAXFunction;return false" doesn't seem to
work.

Feb 20 '07 #4

P: n/a
I love it when people want to use "Ajax" so they can say "we use Ajax".
Ajax is dreamy.
Feb 20 '07 #5

P: n/a
OK I don't think it's convenient to do this using responseXML as the
xhtml document would need to be marked up with the XML namespace and
wouldn't validate (?) as well as a host of other complications.

a better solution from an old thread on this subject:

On 22 Jun 2002, 08:30, "Joe Fawcett" <j...@rightway.co.ukwrote:
1) Parse the responseText property using traditional string processing
techniques, regular expressions etc. to retrieve the text in the div with id
equal to 'Descriptions'
this should be very simple to do... can anyone help me out? a html
page fetched using responseText displays correctly, so this technique
should work?

Feb 20 '07 #6

P: n/a
<br*******@gmail.comwrote:
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?
either using xslt or innerHTML...
--
Une Bévue
Feb 20 '07 #7

P: n/a
On Feb 20, 6:43 pm, unbewusst.s...@google.com.invalid (Une Bévue)
wrote:
<brough...@gmail.comwrote:
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

either using xslt or innerHTML...
--
Une Bévue
depending on whether you and your users have too much bandwidth, or
you have spare server CPU, you could use XHR to bring back a page and
use jQuery or some such to parse through it using javascript in the
client for a specific section of the xmlDOM, or you could write a
proxy script using python or php (the simpleXML functions are very
useful) which would take the request and send back only the content
reuired.
Both ways would mean you wouldn't have to duplicate content. The 2nd
method would be extrememly fast and would not require that your users
had spare CPU and fast internet.

li id="product1"><a
href="product1.html".... to <li id="product1"><a href="#", so that the
XMLHttpRequest can be moved to an onlick event--but if there is no
javascript present, the hard link would remain intact.

Your method of actually changing the href is not needed, as Randy
showed, however his method of adding extra markup in the html is also
not the best way out, instead look into using one of the many
libraries out there which use reg expressions to parse your markup and
attach an onclick dynamically to any given tag, class, or id. These
classes are fast, and are unobtrusive javascript, ie, javascript that
is only present in the DOM if the user agent requests it. Adding extra
markup makes it harder to maintain your xhtml, and causes
accessibility validation issues, and leaves you less time to be polite
to others.

Feb 20 '07 #8

P: n/a
On 20 Feb, 13:08, "shimmyshack" <matt.fa...@gmail.comwrote:

Your method of actually changing the href is not needed, as Randy
showed, however his method of adding extra markup in the html is also
not the best way out, instead look into using one of the many
libraries out there which use reg expressions to parse your markup and
attach an onclick dynamically to any given tag, class, or id. These
classes are fast, and are unobtrusive javascript, ie, javascript that
is only present in the DOM if the user agent requests it. Adding extra
markup makes it harder to maintain your xhtml, and causes
accessibility validation issues, and leaves you less time to be polite
to others.

Thanks for all the info, little out of my depth but I'm looking into
it.

as for adding onclicks dynamically, is
{
var nav = document.getElementById('contactform')
nav.onclick = openform;
}

(which doesn't seem to work with .getElementsByTagName('a') appended?)

preferable to:
var nav =
document.getElementById('contactform').getElements ByTagName('a');
for (var i=0;i<nav.length;i++)
{
nav[i].onmousedown = openform;
}

or is there no real difference? Does the latter consume more cpu due
to the loop?

excuse all the thick questions.

Feb 20 '07 #9

P: n/a
Une Bévue said the following on 2/20/2007 1:43 PM:
<br*******@gmail.comwrote:
>Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

either using xslt or innerHTML...
Neither of which can retrieve a specific div from a source html document
without retrieving the entire document.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 21 '07 #10

P: n/a
ASM
Randy Webb a écrit :
Une Bévue said the following on 2/20/2007 1:43 PM:
><br*******@gmail.comwrote:
>>Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

either using xslt or innerHTML...

Neither of which can retrieve a specific div from a source html document
without retrieving the entire document.
Seems to be quite evident.

Ça semble tout de même assez évident.
Comment insérer un élément d'un document sans préalablement avoir le
document? (pour en extraire le dit élément)

--
Stephane Moriaux et son (moins) vieux Mac déjà dépassé
Stephane Moriaux and his (less) old Mac already out of date
Feb 21 '07 #11

P: n/a
ASM said the following on 2/20/2007 7:12 PM:
Randy Webb a écrit :
>Une Bévue said the following on 2/20/2007 1:43 PM:
>><br*******@gmail.comwrote:

Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?

either using xslt or innerHTML...

Neither of which can retrieve a specific div from a source html
document without retrieving the entire document.

Seems to be quite evident.
Thank you for confirming the obvious :)

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 21 '07 #12

P: n/a
On 20 Feb, 19:52, brough...@gmail.com wrote:
On 20 Feb, 13:08, "shimmyshack" <matt.fa...@gmail.comwrote:
Your method of actually changing the href is not needed, as Randy
showed, however his method of adding extra markup in the html is also
not the best way out, instead look into using one of the many
libraries out there which use reg expressions to parse your markup and
attach an onclick dynamically to any given tag, class, or id. These
classes are fast, and are unobtrusive javascript, ie, javascript that
is only present in the DOM if the user agent requests it. Adding extra
markup makes it harder to maintain your xhtml, and causes
accessibility validation issues, and leaves you less time to be polite
to others.

Thanks for all the info, little out of my depth but I'm looking into
it.

as for adding onclicks dynamically, is

{
var nav = document.getElementById('contactform')
nav.onclick = openform;

}

(which doesn't seem to work with .getElementsByTagName('a') appended?)

preferable to:

var nav =
document.getElementById('contactform').getElements ByTagName('a');
for (var i=0;i<nav.length;i++)
{
nav[i].onmousedown = openform;
}

or is there no real difference? Does the latter consume more cpu due
to the loop?

excuse all the thick questions.
they aren't thick at all, we have to learn at some point.
say you use the behaviour library, which is powerful and easy to use,
use first include the library, and then write some rules for your
links, and then make sur ethey are applied
<script src="behaviour.js" type="text/javascript"></script>
<script type="text/javascript">
var rules =
{
'a.xhr' : function(el)
{
el.onclick = function()
{
alert(this.href);
}
},
'#boo' : function(el)
{
el.onmouseover = function()
{
this.innerHTML = "BOO!";
}
}
};

Behaviour.register(rules);
</script>

these rules would alert the href of any link with a class of xhr such
as
<a href="http://bbc.co.uk/" class="xhr">bbc</a>
or
<a href="http://bbc.co.uk/" class="xhr big">bbc</a>

and would also change the innerHTML of the element with id = boo to
"BOO!"

you can play around with it, but you would exchange the alert for a
call to your ajax script.
It can be very useful, and gets you up and running quickly. As you get
more adventurous you can edit the behaviour library and add custom
methods, or even refine some bits slightly. Head on over to the
"behaviour javascript library" google group for more; or to Ben
Nolan's homepage.

Some people don't like all this library nonsense, they see it as a
threat I suppose and it does takes some getting used to, but once you
recognise the limitations and strengths of each library and learn
their license restrictions, why not. After all, 99% of javascript is
just the same old stuff repeated ad nuseum - you may as well use a
decent pre-written class if, like a calculator, it saves you from mind
numbing and dehumanising coding, which isnt' really coding at all,
just as finding the log(23.2) isn't maths.

Feb 21 '07 #13

P: n/a
br*******@gmail.com said the following on 2/20/2007 8:05 AM:
On 20 Feb, 06:10, Randy Webb <HikksNotAtH...@aol.comwrote:
>brough...@gmail.com said the following on 2/20/2007 6:03 AM:
>>Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?
No.

It appears to be possible to process an XML file fetched using
XMLHttpRequest and extract specific data, so I think this should be
able to be applied to a html document in order to extract the contents
of one div.
Now that is possible. You retrieve the document (the "entire file") and
parse out what you want. Your OQ was if you could retrieve "a specific
div" without "fetching the entire file" and that can't be done with
client side scripting. You could call a server side script that would
return just the contents of an element though.
>That is one crazy idea you have there. Why not:

<a href="product1.html" onclick="someAJAXFunction();return
false">Product</a>

End of problem.

Ah ha! So it doesn't follow the link.
Precisely the purpose of return false in the onclick event handler.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 21 '07 #14

P: n/a
shimmyshack said the following on 2/20/2007 2:08 PM:
On Feb 20, 6:43 pm, unbewusst.s...@google.com.invalid (Une Bévue)
wrote:
><brough...@gmail.comwrote:
>>Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?
either using xslt or innerHTML...
--
Une Bévue

depending on whether you and your users have too much bandwidth, or
you have spare server CPU, you could use XHR to bring back a page and
use jQuery or some such to parse through it using javascript in the
client for a specific section of the xmlDOM,
Re-read the question. It was asked if you could do it without "fetching
the entire file".
or you could write a proxy script using python or php (the simpleXML
functions are very useful) which would take the request and send back
only the content reuired.
If you are going to retrieve just a snippet then why go to the waste of
firing a server side script every time you want to parse an entire file?
Just parse it once, save it in a database, then have the server retrieve
it from the DB.
Both ways would mean you wouldn't have to duplicate content. The 2nd
method would be extrememly fast and would not require that your users
had spare CPU and fast internet.

li id="product1"><a
href="product1.html".... to <li id="product1"><a href="#", so that the
XMLHttpRequest can be moved to an onlick event--but if there is no
javascript present, the hard link would remain intact.
If you change the href to "#" so that "the hard link would remain" then
your page is utterly broken if "no javascript present" and that would
defeat the purpose of trying to satisfy both at once.
Your method of actually changing the href is not needed, as Randy
showed, however his method of adding extra markup in the html is also
not the best way out,
Say again? Thats pure nonsense. "Extra markup"? I was never aware that
onclick="doSomething(this.href);return false" was a lot of "Extra
markup" and it is a lot more cross-browser friendly than trying to write
a script to dynamically attach onclick's to all the links.
instead look into using one of the many libraries out there which use
reg expressions to parse your markup and attach an onclick dynamically
to any given tag, class, or id. These classes are fast, and are
unobtrusive javascript, ie, javascript that is only present in the
DOM if the user agent requests it.
Use a regular expression to parse markup in order to add an onclick to
an element rather than hard coding the markup? And you say my onclick
will make it harder to maintain. Wow.
Adding extra markup makes it harder to maintain your xhtml,
Harder to maintain? I don't believe that. If an onclick="..." gives you
problems maintaining a document then you need to relearn how to maintain
it. Besides, who said anything about xhtml? HTML is the only reliable
version on the web.
and causes accessibility validation issues,
Validators are useless.
and leaves you less time to be polite to others.
But gives you more time to waste the time/effort to find a library and
get it to work in your scenario? Intriguing idea you have there.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 21 '07 #15

P: n/a
On 20 Feb, 17:56, Randy Webb <HikksNotAtH...@aol.comwrote:
Une Bévue said the following on 2/20/2007 1:43 PM:
<brough...@gmail.comwrote:
Is it possible to fetch a specific div from a source html document
using XMLHttpRequest, rather than fetching the entire file?
either using xslt or innerHTML...

Neither of which can retrieve a specific div from a source html document
without retrieving the entire document.
I wasn't clear... it doesn't matter if the entire document is
retrieved from the server by XMLHttpRequest, but I only want one div
displayed in the target once it is fetched.


Feb 21 '07 #16

P: n/a
On 20 Feb, 23:50, Randy Webb <HikksNotAtH...@aol.comwrote:
>
or you could write a proxy script using python or php (the simpleXML
functions are very useful) which would take the request and send back
only the content reuired.

If you are going to retrieve just a snippet then why go to the waste of
firing a server side script every time you want to parse an entire file?
Just parse it once, save it in a database, then have the server retrieve
it from the DB.
this is a good idea... think I will have to come back to this, maybe
put the details in a duplicate XML file for the time being and learn
what's going on. :)

If you change the href to "#" so that "the hard link would remain" then
your page is utterly broken if "no javascript present" and that would
defeat the purpose of trying to satisfy both at once.
This is before I understood return false, but since javascript would
have changed the link from wherever.html to a no-follow "#", the link
would obviously not be broken if no javascript was present--that was
th idea.

Your method of actually changing the href is not needed, as Randy
showed, however his method of adding extra markup in the html is also
not the best way out,

Say again? Thats pure nonsense. "Extra markup"? I was never aware that
onclick="doSomething(this.href);return false" was a lot of "Extra
markup" and it is a lot more cross-browser friendly than trying to write
a script to dynamically attach onclick's to all the links.
mouseover and onclick events do realy clutter menus and make them
harder for clients to maintain. Also, if they are for presentational
effects, then the javascript certainly does not belong in the markup--
I'm sure you would agree with that. This case is perhaps a little
different, but surely it's best to strip all javascript out of the
xhtml if you can (which is incredibly easy to do, if you don't want to
use 'return false', at least!).

Also, once you have the library for that scenario it's easy to fix on
future projects. And while getting a page to display product details
without refreshing the entire document may be a somewhat petty
utilisation of Ajax, I learn how to use the technique--and it's hardly
an abuse if it improves performance, even marginally.

Sorry I wasn't clear in my original question, although I suppose
retrieving all the data and doing the processing on the client side
would defeat the purpose of using this technique, so I probably asked
the right question even if I didn't realise it at the time. ;)

shimmyshack -- thanks for the examples, that's going to be a great
help

Feb 21 '07 #17

P: n/a
On 21 Feb, 09:45, brough...@gmail.com wrote:
On 20 Feb, 23:50, Randy Webb <HikksNotAtH...@aol.comwrote:
or you could write a proxy script using python or php (the simpleXML
functions are very useful) which would take the request and send back
only the content reuired.
If you are going to retrieve just a snippet then why go to the waste of
firing a server side script every time you want to parse an entire file?
Just parse it once, save it in a database, then have the server retrieve
it from the DB.

this is a good idea... think I will have to come back to this, maybe
put the details in a duplicate XML file for the time being and learn
what's going on. :)

The reason that I didn't suggest you use a database or other cache
store was that you mentioned not duplicating content, which made me
think you had flat files.
Caching is a good idea if it really does save you time, or response
time, it might be have been worth it if you were serving data from a
db anyway. In that case you should abstract your script to output the
data in different formats, either XML/JSON or XHTML.
If you aren't using a database and just have a lot of (x)html then
there's no need to add the extra complexity of a slow call to a
database, when a reg exp script will be orders of magnitude faster
that a db call. N calls to a cache residing in a db is still slower
than N calls to a reg exp script.
>
Sorry I wasn't clear in my original question, although I suppose
retrieving all the data and doing the processing on the client side
would defeat the purpose of using this technique, so I probably asked
the right question even if I didn't realise it at the time. ;)

shimmyshack -- thanks for the examples, that's going to be a great
help
Don't worry, I just answered my interpretation of your need;
clarification being predicated on lack of perception or understanding.

re: onclicks and other spurious markup and reg exp etc... separation
is desirable as too much inline js is analogous to inline images -
which aren't worth the lack of http request. Techniques such as DOM
manipulation by js are extrememly useful if you are able to take them
board.
The example I gave is a very very simple one, there are some truly
gorgeous sites which use 100% pure (x)html + Unobtrusive OOjs. I am
writing this in google groups beta, which itself uses these techniques
to parse for classes and dyn change the DOM. You can watch it in real
time if you use firefox and have the firebug extension. Firebug itself
of course uses these techniques! It is just so powerful I cannot
consider ever going back to tables, and inline code.

Feb 21 '07 #18

This discussion thread is closed

Replies have been disabled for this discussion.