Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts

    javascript/ajax variable scope

    Hi not understanding variable scope with ajax generated content... e.g.

    in main page
    Code:
    <html>...etc
    <script language="javascript">
    function _debug(){
     alert('here'); //displays 'here'
     alert(vObj) ; //displays 'undefined'
    }
    </script>
    //blah
    //a hidden div where which LATER is populated with a form via ajax
    <div id="ajax_content_loaded here_later" class="d_hidden"></div>
    //blah
    example of content loaded into 'ajax_content_loaded here_later"' div at some point

    Code:
    <script language="javascript">
    var vObj=new Object();
    vObj['co_name']=['str','1','2','50','','A Name is required'];
    vObj['co_surname']=['str','1','2','50','','A Surname is required'];
    vObj['co_phone']=['str','','','','#PHONE#','A phone number is required'];
    vObj['co_email']=['int','','','','#EMAIL#','A valid email is required'];
    //...etc
    </script>
    
    <form ...etc>
    </form>
    <a href="#" onclick="_debug();"></a>
    basically I cant access vObj from the main page if it is loaded via ajax, it does not know that vObj exists, I assume this is a scopng issue, any ideas please ?
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,132
    Thanks
    12
    Thanked 332 Times in 328 Posts
    Quote Originally Posted by firepages View Post
    basically I cant access vObj from the main page if it is loaded via ajax, it does not know that vObj exists, I assume this is a scopng issue, any ideas please ?
    the very basic approach (without AJAX) does work, so it’s not a scoping issue. but since you mentioned AJAX, it depends how the AJAX code creates that variable (for instance when you load JS code via AJAX, it is not parsed/executed automatically).
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #3
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    Quote Originally Posted by Dormilich View Post
    ... (for instance when you load JS code via AJAX, it is not parsed/executed automatically).
    ok , now understand why adding the debug() test function to the ajax generated output did not work either.
    ..so is there any way to force the browser to parse the javascript ??

    basically onclick a div is populated with a form from a php routine that also generates the validation data required for the requested form... I do have alternatives but this method fits nicely with the form generation scripts, would be nice to get it working...
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #4
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,132
    Thanks
    12
    Thanked 332 Times in 328 Posts
    AFAIK, you need to create a <script> tag that contains or references the JS code and insert it into the DOM.

    alternately, you could use jQuery’s $.getScript()


    Edit: on a side note: it is always bad practise to push everything into the global scope.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,454
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Put the JavaScript at the bottom of the page - that way the HTML it interacts with will exist before it is referenced.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,132
    Thanks
    12
    Thanked 332 Times in 328 Posts
    @felgall: that’s not the problem here.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,454
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by Dormilich View Post
    @felgall: that’s not the problem here.
    I realise that - just telling the OP that they put the script in the wrong place in the page - where they are slowing the loading of the page unnecessarily and where there is a greater potential for problems with scripts.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by firepages View Post
    ok , now understand why adding the debug() test function to the ajax generated output did not work either.
    ..so is there any way to force the browser to parse the javascript ??.
    yes, after you populate the div, use the built in js parser, eval() :
    Code:
    var blocks=ajax_content_loaded here_later.getElementsByTagName("script");
    for(var i=0, mx=blocks.length;i<mx;i++){
      var code=blocks[i].textContent || blocks[i].innerText || "";
      if(code){eval(code); }
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #9
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    Quote Originally Posted by rnd me View Post
    yes, after you populate the div, use the built in js parser, eval() :
    ....
    thanks for that, & I will give it a go, but to be honest I was just doing this to avoid using an iframe in the first place (for reasons I am unsure of ~), ajax just seemed a `cleaner` implementation... beginning to think otherwise now
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #10
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,132
    Thanks
    12
    Thanked 332 Times in 328 Posts
    question, is the code delivered each time that different, that you can’t (at least the library part) load it from the start?
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #11
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    Quote Originally Posted by Dormilich View Post
    question, is the code delivered each time that different, that you can’t (at least the library part) load it from the start?

    The validation library can and will be loaded in every page call its just the details unique to the form that it would be nice to produce at the same time the form is generated.

    Validation for the same form can change depending on its context, e.g. company details for companies are required but not for individuals in that company, so the same form is reused with different validation requirements and some form elements are available to all users and some to admin users etc.

    The routines that build the form already know what validation is required (and handle server-side validation as well) so it seemed ideal to produce the javascript validation requirements at the same time.

    2 options I am thinking about are 1) adding onchange="" to each form since that works (though many form elements already have onchange/keyup events automagically generated) or 2) onsubmit, pass the data via ajax and do the validation at the backend ... then call a script on the main page to add the error messages/highlighting etc, thats kind of ideal but there will be a lag b4 validation, but anyways
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    But then why do you need to load the code via AJAX???

    Or are you also loading the <form>s via AJAX??

    I would have thought you would just use server-side code to produce both at the same time. Or maybe something like this (assuming PHP on the server):
    Code:
    <html>
    <body>
    <?php
    if ( condition )
    {
        $formtype = 17;
        ... output form for formtype 17 ...
    }
    ?>
    ...
    <script src="getValidationCode.php?formtype=<?php echo $formtype; ?>"></script>
    </body>
    </html>
    ???
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,454
    Thanks
    0
    Thanked 632 Times in 622 Posts
    There is never a need to use an Ajax call to load JavaScript - simply attach a new script tag to the page and the JavaScript it references will be downloaded and run automatically without any parsing issues.

    Use Ajax for downloading data - prefereably either in XML or JSON format as Javascript has processing built in to be able to parse either of those formats directly.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #14
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    @Old Pedant && @felgall yes the form is loaded via ajax, and the PHP that generates the form also knows the validation rules for that form in its current context so it made sense to me to generate the javascript rules for validation at the same time.

    The main interface is essentially static and loads forms dynamically as required, its a multi-form page with many optional forms and some of them generated $x times depending on requirements.

    As the validation rules for these forms are dynamic/subjective I can't just pre-load the validation rules in a separate script on the main page.
    My option 2 above will probably work and I can live with it, its just a shame my original preference is so awkward to implement since it was ideal for my porpoises
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Did you try what Felgall suggested?

    Instead of doing load_via_ajax("zamboni.php?form=17")
    try just doing:
    Code:
    ...
    <body>
    ...
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = "zamboni.php?form=17";
        document.body.appendChild(s);
    </script>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •