Forum Moderators: open
jQuery.fn.ajax = function(whichID, url) {
if (url) {
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);
$(document).ready(function() {
$('#' + whichID).load(
this_url + '?' + $.param({ query_string })
);
});
}
else document.getElementById(whichID).style.display = 'none';
}
// Usage
<div onClick="$().ajax('id', 'http://www.example.com')"></div>
function ajax(whichID, url) {
if (url) {
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);
$(document).ready(function() {
$('#' + whichID).load(
this_url + '?' + $.param({ query_string })
);
});
}
else document.getElementById(whichID).style.display = 'none';
}
// Usage
<div onClick="ajax('id', 'http://www.example.com')"></div>
// UNTESTED !
jQuery.fn.ajax = function(url) {
if (url) {
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);
$(document).ready(function() {
$(this).load(
this_url + '?' + $.param({ query_string })
);
});
}
else $(this).css('display', 'none');
}
// Usage
<div onClick="$('#id').ajax('http://www.example.com')"></div>
After calling $('#id'), this (within a chained jQuery function) would be the jQuery object, so you wouldn't need to do $(this).load, instead you would just use this.load.
jQuery.fn.ajax = function(url) {
var whichID = this;
if (url) {
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);
$(document).ready(function() {
$(whichID).load(
this_url + '?' + $.param({ query_string })
);
});
}
else $(whichID).css('display', 'none');
}
Just FYI, I tested it and this didn't work for me
Oh, right. That's because you're calling it within another function (the anonymous function passed to $(document).ready). The "this" variable within that function is a running in a different scope. By assigning whichID to this, the inner function can access it thanks to the closure, and doesn't get confused about what "this" really is. :)
<body>
<script>
var foo = document.getElementById('foo');
// element with id foo hasn't loaded yet, so foo = null
foo.innerHTML = "foo bar"; // causes error
</script>
<div id="foo"></div>
</body>
<body>
<script>
$(document).ready(function () {
var foo = document.getElementById('foo');
// this function doesn't execute until the DOM has loaded
// so element with id foo can be found nowl
foo.innerHTML = "foo bar"; // no error
});
</script>
<div id="foo"></div>
</body>