March 23, 2012

jQuery can't use $.ajax on Dynamically loaded content

Question by Abhishek Biswal

I was working on a Login Form ( AJAX ) enabled. When a use clicks on link, that Login box, as a floating modal appears. The Content of that Login box is loaded from another page using jQuery’s $().load function. On click of the link the Login Box loads. But, when I implemented AJAX submitting on that form:

$(document).ready(function(){
    $("form#loginbox").submit(function(e){ e.preventDefault(); /*AJAX function here*/ });
});

But the form is submitted normally, without following what is given in the function, that is ( Prevent the Default – Submitting and use AJAX ). so does that mean the Loaded content is not considered inside DOM or the script cannot read it? I load the content only once:

$(document).ready(function(){
    if($("#loadedform").html() == "")
    { $(this).load('/load/login.html'); }
    $(".login-modal').slideDown('slow');
});

The structure:

<div class="login-modal"><div id="loadedform"></div></div>

the content to be loaded:

<form id="loginbox" method="post" action="xyz.html">
<!-- INPUT Boxes and Submit Button -->
</form>

Answer by Richard Dalton

Change

$("form#loginbox").submit(function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

to

$('#loadedform').on("submit", "form#loginbox", function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

or if you’re using a version before 1.7:

$('#loadedform').delegate("#loginbox", "submit", function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

This is because the event is registered when the page is loaded, so when your form is loaded it does not have the event attached. This change will register the event at a higher level in the dom so any new content will also work.

It also looks like you should change the code that loads the form to:

if($("#loadedform").html() == "") { 
    $("#loadedform").load('/load/login.html'); 
}
$(".login-modal').slideDown('slow');

Otherwise you won’t be loading it into the right place.

Answer by Starx

You have to delegate over the dynamic elements using .on() method

$(document).on("submit","#loginbox", function() {
 e.preventDefault(); 
 /*AJAX function here*/
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!