user632347
user632347

Reputation: 835

How to run a function using live() outside ajax()?

I want to run a jquery function on html loaded through ajax. How can I do it. Please see that I cant use it inside $.ajax() because this ajax() function is already managed by another module in the system and I cant hook into it. I tried the following, but its not changing the value of input field loaded via ajax. Any idea?

$(document).on("ready", function(){
    run_my_function();
});
function run_my_function(){
    $('selector_on_html_loaded_through_ajax').val('Hi');
}   

Upvotes: 0

Views: 64

Answers (1)

AaronAsAChimp
AaronAsAChimp

Reputation: 529

There is a pseudo-event in jquery that will allow you to run code when any, jquery initiated, ajax request is successful. There maybe more efficient methods, like in the ajax success handler of the request you're making.

$.ajaxSuccess(function () {
    $('selector_on_html_loaded_through_ajax').val('Hi');
});

/// or ///

$.ajax({
    'url': 'http://example.com/this/is/my/request',
    'success': function () {
        $('selector_on_html_loaded_through_ajax').val('Hi');
    }
});

Update: Another option

Another option would be to use DOM mutation events. The only problem is that they are deprecated. This question describes how to use them cross platform.

Upvotes: 1

Related Questions