XMLHttpRequest to fetch a specific div

B

broughcut

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!
 
R

Randy Webb

(e-mail address removed) 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.
 
B

broughcut

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('div2')

}
}

XMLHttpRequestObject.send(null);
}
}
 
B

broughcut

(e-mail address removed) said the following on 2/20/2007 6:03 AM:


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').getElementsByTagName('a');
for (var i=0;i<nav.length;i++)
{
nav.onmousedown = someAJAXFunction;
}

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

broughcut

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:

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?
 
U

Une Bévue

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...
 
S

shimmyshack

either using xslt or innerHTML...

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.
 
B

broughcut

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').getElementsByTagName('a');
for (var i=0;i<nav.length;i++)
{
nav.onmousedown = openform;
}

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

excuse all the thick questions.
 
R

Randy Webb

Une Bévue said the following on 2/20/2007 1:43 PM:
either using xslt or innerHTML...

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

ASM

Randy Webb a écrit :
Une Bévue said the following on 2/20/2007 1:43 PM:

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)
 
S

shimmyshack

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').getElementsByTagName('a');
for (var i=0;i<nav.length;i++)
{
nav.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.
 
R

Randy Webb

(e-mail address removed) said the following on 2/20/2007 8:05 AM:
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.
Ah ha! So it doesn't follow the link.

Precisely the purpose of return false in the onclick event handler.
 
R

Randy Webb

shimmyshack said the following on 2/20/2007 2:08 PM:
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.
 
B

broughcut

Une Bévue said the following on 2/20/2007 1:43 PM:



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.
 
B

broughcut

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.

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
 
S

shimmyshack

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top