[Javascript] AJAX and variable assignment?

Casey casey.lists at caseyftw.com
Sun Apr 26 15:16:17 CDT 2009


On Sun, Apr 26, 2009 at 5:27 AM, Javascript List User <jsuser at noopy.org> wrote:
> Hello,
>
> I'm using AJAX (prototype.js) and I'm having problems wrapping my head
> around how to assign a variable in my code -- because no matter what I
> try the variable remains undefined.  I assume this is because of AJAX
> being asynchronous but am not quite sure how to assign variables in
> this context.  Ideally I'd like to *not* set asynchronous to false
> (and I'm not even convinced that asynch being false will work w/Firefox
> 3.0.x).
>
> My end goal is to build a menu from innerHTML of an object that was
> updated via AJAX.  Given what I've observed above, it appears that
> while I can use AJAX to update the UI with the text/HTML that I'd
> intended, when I look at object.innerHTML, it shows the *old* HTML not
> the *new* HTML that I'd put inside of it.  For example:
>
> <html>
>  <head>
>   <title>Ajax test</title>
>
>   <script src="javascript/prototype.js"></script>
>   <script type="text/javascript">
>       var assign_it = null;
>
>       function do_ajax() {
>           var url = '/testjs1.cgi';
>           var pars = 'ajax=1'
>           var myAjax = new Ajax.Request(
>               url,
>               {
>                   method: 'get',
>                   parameters: pars,
>                   onComplete: function(http) {
>                       assign_it = http.responseText;
>                       $('starter').innerHTML = assign_it;
>                   }
>               });
>           alert("after " + " " + assign_it + " " + $('starter').innerHTML);
>       }
>   </script>
>  </head>
>
>  <body>
>   <p id="starter">I am the start condition.</p>
>   <input type="submit" onclick="do_ajax()"/>
>  </body>
> </html>
>
> In the HTML above, do_ajax() updates the UI with the output of my CGI
> program (the string "I've been touched by AJAX") but
> $('starter').innerHTML still contains "I am the start condition".  The
> same holds true when I look at the DOM Inspector in Firefox 3.0.x.
> :-(
>
> Does anyone have any suggestions as to how I can do the variable
> assignment that I propose?

What happens is
 1) doAjax() is called.
 2) The request is sent.
 3) The alert box pops up.
 4) doAjax() ends.
   ...
 5) (later) The response is received.
 6) The onComplete function is called.
 7) DOM is changed, and assign_it is set.

So basically, you called the alert too early. Put the alert in your
onComplete function.

>
> --
> NP
>
> --
> Nathan Patwardhan
> _______________________________________________
> Javascript mailing list
> Javascript at lists.evolt.org
> http://lists.evolt.org/mailman/listinfo/javascript
>



More information about the Javascript mailing list