Lee Kelleher

Accessing the jQuery DOM in an Ajax callback

Posted on

Whilst developing the admin pages for Pez, I wanted to add some nice features to the UI. My first choice for a JavaScript framework is jQuery. I’ve used other frameworks before, (like mootools, script.aculo.us and YUI), but I just seem to get on better with jQuery, (although mootools is a very close second).

Last night I was playing around with the Ajax/jQuery.get() method – it was the first time I’d used it, and was having some difficulty understanding how access the jQuery DOM object in the callback function.

At first I was taking the wrong approach, I was trying to do this all in the onClick event of an anchor link:

onclick="javascript:$.get('index.php', { key: $('#source-input-id').val() }, function(data){ $('#target-input-id').val(data); });"

But that didn’t work … and I’m not fully sure why … but anyway, I carry on …

I started to look at the this keyword to see if that would help. Learning jQuery’s What is this? post clarified a lot of my confusions, (in that with the Ajax callbacks, the this keyword/object is outside the jQuery DOM, but contains details of the call itself), however I was still no closer to the solution I wanted.

At this point I changed how I was using the <strong>$.get()</strong> method. I created a wrapper function for jQuery calls:

function get_value()
    $.get('index.php', { key: $('#source-input-id').val() }, function(data){

This approach meant that I could reference the jQuery DOM object from within the Ajax callback function.

There is probably a hundred other ways of doing this using jQuery – or could be even simpler with another JS framework – but I got it working nicely in the end… Happy Days!