2

So I am using an AJAX loader on my WP installation and one of the pages I am loading has a script in it.

<div id="register-form">
    <div id="register-one"></div>
    <div style="text-align:center;padding-top:10px;"></div> 
    <div class="horizontal-rule"></div>
    <div id='register'>
        <div id="register-character">
        </div>
    </div>

    <div class="post">  
        <form action="" method="post" id="register-form" >
        What's your Name:
            <input class=in id='register_name' name="register_name" onkeydown='register_step1_keydown();' onkeyup='register_step1_keyup();'>
            <input class="next-submit-button" type="submit" id="register-step-one" value="" />
            <input type="hidden" name="submit" />
        </form>  
    </div>
</div>

<script type="text/javascript">

$("#register-step-one").click(function() {
    $.ajax({
      type: "POST",
      success: function() {
        $('#register-form').html("Test");
      }
     });
    return false;
});

</script>

The issue is however, when the page is loaded through the AJAX, the script doesn't work. Yet if I refresh the page the script works. Obviously the script doesn't like running from an AJAX call.

Is there a way to make the script work when it is loaded through an AJAX call? I know I could put the script in to the main page's footer or something but I was hoping I could get around this as I will end up with a ton of scripts in the main page.

Tenatious
  • 849
  • 4
  • 12
  • 32

1 Answers1

3

Before anything else, you should wrap your function in a .ready() to ensure all DOM elements are loaded before you do something to those elements

Also, scripts within HTML that are returned via ajax functions in jQuery are executed only when the HTML is appended in the DOM. Since you did not append the html containing the code, the script in that returned content won't run.

Take a look at the .ajax() function's parameters, under dataType

dataType:

...

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

...

Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • I'm not sure this answers my question? The script on that page works fine when it is loaded through the URL bar but not when the page is loaded through an AJAX request from the main page's nav bar. – Tenatious Nov 04 '12 at 14:52
  • @Tenatious check your console. And like I said, unless the HTML from the Ajax is appended on the page, the scripts on that loaded HTML won't work. Also, you are loading an entire page. There might be *other* scripts that may cause others not to run, and not just yours. – Joseph Nov 04 '12 at 15:05