0

I'm making a sign up system. After user successfully sign up, form->ajax->php, ajax adds html to a premade empty message div.

$("#register_form").submit(function(event) {
    var $data = $(this).serialize();
    var result = "";

    $.ajax({
        cache   : false,
        type    : "POST",
        url     : "php/register.php",
        data    : $data,
        success : function(response) {
              if(response === "OK"){
                  result  = "<div class='alert alert-success'>You have successfully registered!<br/>";
                  result +=     "Please check your mailbox for the activation link. It may take a few minutes.<br/>";
                  result +=     "<a id='resend'>Resend Confirmation Email</a>";
                  result += "</div>";
                  $("#register_form").slideUp(500);
              }
              else{
                  result = '<div class="alert alert-danger">' + response + '</div>';
              }

              $("#register_response").html(result);
              $("#register_response").slideDown(500);
        }
    });

    event.preventDefault();
});

I put the 'resend confirmation email' in there, just an empty link waiting to be clicked on. But it seems the sign up page's javascript (which is the same file the above script is in, I did $("#resend").click(...) ) doesn't apply to it. Where do I put the javascript so that this will work?

Also, if this is not a good way to add html using javascript, what's a good way to achieve this?

J13t0u
  • 811
  • 1
  • 8
  • 19

1 Answers1

1

Try this:

$("#register_response").on('click','#resend',function(){
  ///Your code

});
The Process
  • 5,913
  • 3
  • 30
  • 41
  • does `register_response` element exist before `ajax` call? – The Process Mar 03 '16 at 01:52
  • Yes, it's an empty div – J13t0u Mar 03 '16 at 01:55
  • here you can see, appended result after `4sec`, and than trigger `click` event http://jsbin.com/civixig/edit?html,js,console,output – The Process Mar 03 '16 at 02:08
  • I don't know why it didn't work before, probably the host didn't save it correctly. But it's working now. Why do I have to do this? New elements from ajax do not get event bind on them? – J13t0u Mar 03 '16 at 02:50
  • Because you're binding event `(click)` to the `element` that doesn't exist at that time. This way, you are `binding click event` on his `container` and when `click occur`, it is checking if it was on the `'#resend' element` – The Process Mar 03 '16 at 02:53