Question

I'm trying to watch for an element to load on the page from an ajax call. I don't have access to the jquery that's making the ajax call. So, when some new html is loaded onto the page, I'd like to apply some changes to it.

I'm currently trying to use the .load() function:

$( '.autosuggest_keyword' ).load( 
    function()
    { 
        $( this ).val( 'load test' );
    }
);

Which isn't doing anything. I even tried making that a live binding, which doesn't really make sense, but I thought I'd give it a try.

The selector is correct.

Any ideas?

Was it helpful?

Solution 5

I was able to get access to the original ajax call, so this question is moot now. I'm leaving it up for others to find, however, in case one of these answers helps them.

OTHER TIPS

The .load() function expects an URL to which to send the AJAX request, fetch the data from the server and update the given element in the selector. So you need to pass an URL:

$('.autosuggest_keyword').load('/foo');

Do you know what is calling the inital ajax? if so you could call a function using the same event. Though this could cause some confusion if you're trying to change something that the ajax is loading.

Duck punching might be the answer:

should('duck-punch ajax success handler', function() {
    var origAjax = $.ajax;

    $.ajax = function(settings) {
        if(settings.url === 'the/request/page') {
            var origSuccess = settings.success;
            settings.success = function(responseHTML) {
                origSuccess.call(this, responseHTML);
                //apply some changes to html
            }

        }
        origAjax.call(this, settings);
    }
});

When you call .load, it's binding that event handler to elements that match your selector at the time you're calling it. Since the element is added after that, it's never bound. The .live function solves this problem by binding to currrent and future elements matching a selector. I think what you want is something like this (untested):

$( '.autosuggest_keyword' ).live('load', 
    function()
    { 
        $( this ).val( 'load test' );
    }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top