Link to home
Start Free TrialLog in
Avatar of newbie_coder
newbie_coderFlag for Canada

asked on

AJAX: getElementById of another page on same server?

Hi experts,

I have 2 pages on the same server. The 1st page contains a bunch of blank form fields like Name/Address/Country. The 2nd page contains actual values of Name/Address/Country in DIVs.

Now is it possible to make a button on the 1st page that when you click on it, it retrieves the values in the DIVs of the 2nd page and fills that date into the form fields of the 1st page accordingly?

Just looking of AJAX samples of how this can be done, thanks.
Avatar of Jai S
Jai S
Flag of India image

if you are opening the FIRST PAGE FROM THE SECOND PAGE...then it is possible...
you can specify window.document.opener.forms[0].fieldname.value...
this is done using normal JSCRIPT...
Avatar of b0lsc0tt
If the info you want is part of the html and not user entered (i.e. in a form) then you don't need the other page to be in a pop-up or related window.  AJAX is what you need.

What is that other page like?  Are these server pages?

One of the best explanations and simplest examples I have found on the net is at http://www.skeymedia.com/programming/classic-asp-and-ajax-tutorial/.  There is also a good explanation on what AJAX is at http://en.wikipedia.org/wiki/Ajax_%28programming%29.  The reference site W3Schools has a good section on AJAX at http://www.w3schools.com/ajax/default.asp.

If you want help with implementing this then I need details and code.  The code for both pages and info on which fields relate to which divs.  The basic idea would be to have the AJAX script get the other page and then parse the  response to get the div contents you need.

Let me know how this helps or if you have a question.

bol
Avatar of newbie_coder

ASKER

Hi Sage. Okay, here's an example of the 2 pages (both on same server, just don't have access to the backend DB, so would have to use javascript to retrieve front-end content from another page)

1.) /form_page.html

<html>
<head>
<script>
function retrieve() {
  // feed me   : )
}
</script>
</head>
<body>
<form>
Name: <input type="text" name="namefield" value="">
<br>
Address: <input type="text" name="addfield" value="">
<br>
Country: <input type="text" name="cntryfield" value="">
<br>
<input type="text" name="sid" value="" maxlength="3"> &nbsp; <input type="button" value="Retrieve" onclick="retrieve();">
</form>
</body>
</html>

- - - - - -

2.) /info.aspx?id=300

<html>
<body>
<div id="fullname">John Doe</div>
<div id="address">9876 Drive Way</div>
<div id="country">USA</div>
</body>
</html>

- - - - - -

All the fields in the first page are blank, so when one enters the ID number and then click the "Retrieve" button, it should load /info.aspx?id=### into memory, get each of the IDs by using getElementById and fills in the form fields on the current page.

So is this possible? I would like to do this without frames/iframes so that the page stays fairly clean-looking and not cluttered, thanks!
It is possible and with the setup of the aspx page should be pretty easy.

Do I understand correctly that each "answer" is in its own div with a unique id on the aspx page?  Are those the only divs on the aspx page (the ones with field "answers")?

I would suggest that you using the id as the name in the form fields.  It isn't required but would make the javascript code (the parsing part) easier.  What do you think?

How do you want to proceed?  What do you need from me to answer this and get this working?  You can pretty much cut and paste the "AJAX" part of the example link I provided earlier.  I suggest you start there and then have that script just fill a div with all of the response from the AJAX script.  This will show you that part is working.  Then work on getting the field values from the AJAX response.

You answers to my questions above will help with this but basically you should be able to parse the response and assign the values with javascript something like ...

var body = xmlhttp.responseText;
var divs = body.document.getElementsByTagName('div');
var frm = document.forms[0];
for (var i=0; i<divs.length; i++) {
    if (frm.elements[divs[i].id]) {
        frm.elements[divs[i].id].value = divs[i].value;
    }
}

That is the basic idea or the part to parse the response and get the value into the fields.

Let me know how I can help or how this works.  This is definitely possible, the details will just determine how much work it is. :)

bol
Okay, here's what I have so far (taking snippets from W3schools):

<html>
<title>Retrieve Info</title>
<body>
<script type="text/javascript">
function retrieve() {
      var xmlHttp;
      try {
            xmlHttp = new XMLHttpRequest();
      }
      catch (e) {
            try {
                  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                  try {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (e) {
                        alert("Your browser does not support AJAX!");
                        return false;
                  }
            }
      }

      xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                  var body = xmlHttp.responseText;

                  var fn = body.document.getElementById('fullname').innerText;
                  var add = body.document.getElementById('address').innerText;
                  var cty = body.document.getElementById('country').innerText;
      
                  document.form1.namefield.value = fn;
                  document.form1.addfield.value = add;
                  document.form1.cntryfield.value = cty;
            }
      }

      var nmt = document.form1.sid.value;
      var url = "info.aspx?id=" + nmt;

      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
}
</script>
<form name="form1">
Name: <input type="text" name="namefield" value="">
<br>
Address: <input type="text" name="addfield" value="">
<br>
Country: <input type="text" name="cntryfield" value="">
<br>
<input type="text" name="sid" value="" maxlength="3"> &nbsp; <input type="button" value="Retrieve" onclick="retrieve();">
</form>
</body>
</html>

- - - - - -

It's not working and gives me an error at the line:

      var fn = body.document.getElementById('fullname').innerText;

The error message says: "document" is null or not an object. But clearly info.aspx exists. I've even tried a full path with domain name as well, same error. So I'm not sure what is wrong with my code.
I think the problem is an error of mine.  Try ...

      var fn = body.getElementById('fullname').innerText;

The document part is probably the problem.  It is late though and I need to go so I might be wrong. :) Let me know how that works or if you have a question.

bol
Okay, I've removed the "document" from each of those lines. It gives me a different error now (referring to the same line):

      Object doesn't support this property or method

Not sure how to fix that. And how do I know that info.aspx is loaded correctly into memory with the xmlHttp.responseText so that it can be read?
>> how do I know that info.aspx is loaded correctly into memory <<

Let's test that first.  Remove or comment out the code for "parsing" the response from aspx.  Then just use an alert or make a div with a unique id and "send" the results to the div.  Let me know if you need specifics on doing this.  The basic idea would be something like ...

      xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                  alert(xmlHttp.responseText);

For the other issue, what browser are you using?  The innerText "property" only works in IE.  You should avoid using it and that might be why you are getting the error.  Instead use innerHTML.  Be prepared to get html tags, etc too but that isn't a problem if you know what you are getting.  In this case there should be no issue at all.  Let me know if that simple change (innerText to innerHTML) fixes it.

Let me know how this works or if you have a question.

bol

Okay, I've tried using the alert and it shows the HTML contents of info.aspx nicely and everything looks good and loads fast too.

Then I put all the parsing code back using innerHTML and the problem occurs. In IE6 and IE7, it says the same error ("Object doesn't support this property or method") referring to the same line where this starts:

      var fn = body.getElementById('fullname').innerHTML;

In FireFox, nothing happens when the script runs; even though it worked properly when the alert code was in place.
...also, just doing some searching, and this guy says it's not possible: http://www.thescripts.com/forum/post2648190-3.html

How would I get around this? Could the xmlHttp.responseText be parsed into an invisible IFRAME and then have my form_page.html use iframe[0].getElementById  ??
That guy gave up too quick.  It does look like there is a limit to getElementById().  There are a few alternatives though and no reason to give up and go to an iframe. :)

The next easiest way would be ...

                  var body = xmlHttp.responseText;
                 
                  var divs = body.getElementsByTagName('div');
                  for (i=0; i<divs.length; i++) {
                        switch (divs[i].id) {
                              case "fullname":
                                    var fn = divs[i].innerText;
                                    break;
                              case "address":
                                    var add = divs[i].innerText;
                                    break;
                              case "country":
                                    var cty = divs[i].innerText;
                                    break:
                              default:
                                    break;
                        }
                  }
                  document.form1.namefield.value = fn;
                  document.form1.addfield.value = add;
                  document.form1.cntryfield.value = cty;

That is another way to do it.  Let me know if you have a question or how that works.

bol
Same error message. I'm sure that guy is right as it sounds like "responseText" retrieves everything as plain text and "responseXML" reads an XML file. There's not "responseHtml" but search for the term gives some nice examples I'll try out later. Or maybe the info.aspx needs to be generated as an XML file. Thanks anyways.
ASKER CERTIFIED SOLUTION
Avatar of b0lsc0tt
b0lsc0tt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In my 2nd post from the top, "info.aspx?id=300" is exactly as it is. Just different innerText depending on the ID number. The DIVs are in the same order and layout. Again, I don't have access to the page unfortunately, but I can get the "real programmer" to make an XML version for me, then I can use the XMLDOM parser thing.

You can keep helping out if you'd like but I'm playing around with the responseHtml code I found in the 2nd Google results. It's a lot harder for me to understand (many more functions) but I might be able to get it to work later.
>> Again, I don't have access to the page unfortunately, <<

I had forgotten that you said that.  Part of your more recent post made me think changing it was an option.

To do the method with the expression try ...

                  var body = xmlHttp.responseText;

                  var arResult = body.match(/<div id="[^"]+">([^<]+?)<\/div>[\s\S]*<div id="[^"]+">([^<]+?)<\/div>[\s\S]*<div id="[^"]+">([^<]+?)<\/div>/g);
              if (arResult && arResult.length == 4) {
                    document.form1.namefield.value = arResult[1];
                    document.form1.addfield.value = arResult[2];
                    document.form1.cntryfield.value = arResult[3];
                  }

Let me know how that works.  As long as the order is like above and no new elements are added in that block of divs this will get what you need.

bol
Just tried your code. It doesn't seem to be working. No javascript error messages are given in IE6 IE7 or in FireFox. You can actually try it yourself taking the page code from my 2nd post at the top. Don't worry about it too much as we're gonna try changing the info.aspx to generate an XML document instead.
If you are going to change the info.aspx page and aren't already familiar with working in xml then just simplify the response to be just the minimum.  For example the values separated by commas.  You could still use the responseText property and would not need to worry about parsing html, just very basic text.  A simple split could be used if it were comma separated.

I did test, as much as possible, the code and expression I suggested.  I used the html from the 2nd post to test it.  Let me know how changing the aspx file works out.  I can look again at the expression or script to see if there is an error but your html in the 2nd post was what I needed to even make the expression. :)

Let me know what else I can do to help or if you have a question.

bol
I'm glad I could help.  Thanks for the grade, the points and the fun question.

bol