?
Solved

AJAX: getElementById of another page on same server?

Posted on 2007-09-30
18
Medium Priority
?
954 Views
Last Modified: 2008-01-09
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.
0
Comment
Question by:newbie_coder
  • 9
  • 8
18 Comments
 
LVL 14

Expert Comment

by:Jai S
ID: 19988851
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...
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 19992676
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
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 19996795
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!
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 19999847
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
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20004413
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.
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20004486
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
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20008336
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?
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20008451
>> 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

0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20008926
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.
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20009324
...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  ??
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20009723
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
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20010355
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.
0
 
LVL 54

Accepted Solution

by:
b0lsc0tt earned 548 total points
ID: 20010410
No reason to give up yet.  Thanks for trying that method.

Can you change what the info.aspx file provides?  If so (i.e. it is only used for this page and not a page on its own) then the easiest is to simplify what it sends.  We can have it send just what we need and responseText will work fine.

I haven't done a lot in XML but once did play with something that could be an option.  You use the XMLDOM parser in that case but I will save that for a last resort.  The contents don't actually need to be XML but are just handled that way (i.e. well formatted html can work, etc).

Will the divs be in the order you showed above?  If so then I could probably make an expression to get what we want.  Let me know if the layout of the response is the same all the time.  Also that the divs will not contain other html.  Confirm this stuff and I can make the code.

If you are still interested in getting this to happen then let me know which of the options above will work.  If you can modify the info.aspx file then that will be easiest.  The next, assuming the things I mentioned are true, would be the expression.  Finally we could use the XML parser if we have to.

Let me know if you have a question.

bol
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20010642
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.
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20010790
>> 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
0
 
LVL 1

Author Comment

by:newbie_coder
ID: 20017023
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.
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20017397
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
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20028460
I'm glad I could help.  Thanks for the grade, the points and the fun question.

bol
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question