View Full Version : Getting info from another page using ajax

rnd me
01-29-2013, 02:02 AM
One question i see on here a lot is "how do i pull a div on a different page into the current page?"

The responses are often complex or they pass the buck: try using jQuery, use PHP, use a CMS, double-code both divs, etc...

I didn't like any of those answers, and knew it couldn't be that difficult to do with a tiny bit of javascript. There really is no short answer, until now.

function getPage(url, from, to) {
var cached=sessionStorage[url];
if(!from){from="body";} // default to grabbing body tag
if(cached){return elm.innerHTML=cached;} // cache responses for instant re-use re-use
if(to && to.split){to=document.querySelector(to);} // a string TO turns into an element
if(!to){to=document.querySelector(from);} // default re-using the source elm as the target elm

var XHRt = new XMLHttpRequest; // new ajax
XHRt.responseType='document'; // ajax2 context and onload() event
XHRt.onload= function() { sessionStorage[url]=to.innerHTML= XHRt.response.querySelector(from).innerHTML;};
XHRt.open("GET", url, true);
return XHRt;


URL : Location of remote resource ,
FROM : CSS selector of source tag on remote page ,
TO: CSS selector of destination tag

the source defaults to "body" if the from CSS selector is not specified, and the to CSS selector defaults to the from value if not specified.

Example uses:

EX 1. (typical use) virtually grab the next page:
when on http://www.codingforums.com/forumdisplay.php?f=2
show table from http://www.codingforums.com/forumdisplay.php?f=2&order=desc&page=2

"#inlinemodform" );

notice how "#inlinemodform" is repeated? It's moving the same block to the same block on another page.
You can omit the 2nd CSS selector when it's a duplicate, so the following is 100% equivalent to the above:

"#inlinemodform" );

EX 2. (defaults) replace this whole page with another post i wrote a while back:


EX 3. (external content) inject event listings from UIUC into the current page:

getPage("//www.it.illinois.edu/news/", ".list.events.vcard.clearfix", ".tcat" )

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum