JQuery $(document).ready ajax load

Craig picture Craig · Jul 28, 2010 · Viewed 21.6k times · Source

I looked at quite a few of the related questions and I must be asking this completely different as I saw only a few that seemed to relate. I am loading an entire middle div via JQuery Ajax call and I simply want to be able to do some automatic JQuery on that new area like $(document).ready allows when a DOM is being loaded. I read that livequery would do this, but I figured there would be a way built into it. I am trying to add a date picker to a input field right a the beginning.

This is the content that will call for the content in the backend which will then pull some specific section.

$.post("ReportingWizard",$("#wizard_form").serialize(), function (data) { setData(data); });

function setData(data) {
divElement.innerHTML = data;
$(activeTab).fadeIn(); //Fade in the active content
$(".wizardBody").fadeIn();
}

Inside the file that is being put at that divElement will have a JQuery method that needs to be run to change the html inside it.

Answer

Matt picture Matt · Jul 28, 2010

Register the events in the callback of the AJAX function.

If you're using .load() to do load the middle div, place your jQuery code directly in the callback:

$('#middleDiv').load('/fish.php', function () {
    $('#someDiv').fadeIn(300); // ? whatever
});

If you're using some of the other AJAX functions, place your jQuery code after the line where you add the elements to the DOM in the callback:

jQuery.get('/fish.php', function (response) {
    $('#middleDiv').html(response);

    $('#someDiv').fadeIn(300); // ? whatever
});

If it's events you want to bind, you might look at using .on() (or .delegate() or .live() if you're using the older versions of jQuery, which were around when this question was originally written). You can see a comparison of these various methods here.

These methods allow the binding of events to elements even when they are not yet present in the DOM; which means you can bind the events in your $(document).ready() block, even though the elements aren't registered in the DOM yet.