Oct 2, 2008

jQuery - update DIV's HTML dynamically

jQuery is a JavaScript library, downloadable here. It uses AJAX calls to get external data. Retrieving this data is simple - I used two functions:
function geturl(addr) {
var r = $.ajax({
 type: 'GET',
 url: addr,
 async: false
}).responseText;
return r;
}

function changediv() {
$('#div_id').html(geturl('http://www.example.com'));
}


UPDATE: For asynchronous ajax calls see example in the comments below.

5 comments:

Unknown said...

thnx 4 ur nice little script!

I use it @ quizlet.nl to refresh some bits of the frontpage.

codysoyland said...

Synchronous requests lock the browser, so this is better rewritten with a callback:

$.ajax({
type: 'GET',
url: "http://www.example.com",
success: function (response) {
$('#div_id').html(response);
}
};

(untested, but I think that should work)

jeancaffou said...

Indeed. Or better yet, you can just pass the function's reference to the success parameter.

function async_get(addr,func) {
$.ajax({
url: addr,
success: func
});
}

This way you can do whatever with the data when it loads.

async_get('http://example.com',function(data){$('#mydiv').html(data)});

Anonymous said...

Testing

Anonymous said...

thanks for the code