0

After fully loaded the HTML DOM I am calling ajax on form submit and the result I got is:

<a data-nonce="https://hypley.com?wp_nonce=2db70bc9fb" id="resend_email">here</a></strong>

Now, again I want to call ajax on that link click:

$("#resend_email").on("click", function (e) {
    e.preventDefault();
    alert(1);
    var user_login = $("#user_login").val();
    console.log( user_login );
});

But it's not working, I mean at least not showing me the alert.

Do you know why, how can I solve it?

Shibbir
  • 1,963
  • 2
  • 25
  • 48
  • To add to @David 's answer: you can do what David suggested, or you can add your event listener that you have now when, and only when, the AJAX call has completed AND the anchor tag has been inserted into the DOM. Delegation doesn't care about theses things, which is great, but I thought I would help your understanding about why your current method is failing. – Zeke Willams Sep 16 '20 at 15:12

1 Answers1

2

I assume you setup your JS before the AJAX runs, right? In that case: Use a delegated event instead.

$(document).on("click", "#resend_email", function (e) { // <-- see second argument of .on
  e.preventDefault();
  alert(1);
  var user_login = $("#user_login").val();
  console.log( user_login );
});

The reason it doesn't work is, that jQuery cannot find the element with the id #resend_email when the DOM is constructed and the jQuery collection returned from $('#resend_email') is empty (it has a length of 0). This means, the click handler you attach has no element it can be attached to, so jQuery does not attach an event listener.

In short: Delegated events solve that issue by attaching the listener to an already existing element and, when the handler is invoked, scanning for the event target element. If it matches the specified selector, the handler is invoked. You can read about delegated events and how the work in the jQuery docs.

David
  • 3,552
  • 1
  • 13
  • 24
  • If event delegation is the answer (as it appears to be) then you should really link to the duplicate as this gets asked at least 10 times a day (anecdotally) – freedomn-m Sep 16 '20 at 15:28
  • I already have the wrapper like this `$(document).ready(function(){ ..... ` so shall I use this then `$("#resend_email").on("click", "#resend_email", function (e) {...` – Shibbir Sep 16 '20 at 16:48
  • can you tell me please @David – Shibbir Sep 16 '20 at 17:02
  • @creativeartbd No, you shouldn't. The thing is, `$(document).ready` waits until the _initial_ DOM is constructed - however, your DOM isn't complete until the AJAX arrives which is _after_ the construction of the initial DOM. – David Sep 17 '20 at 06:32