tags:

views:

389

answers:

2

I find myself doing 2 things quite often in JS, at the moment using jQuery:

The first is the populating of an HTML element, which might look like:

$.get('http://www.example.com/get_result.php', { id: 1 }, function (data) {
    $('#elementId').html(data);
});

The second is populating a select element with a JSON result, such as:

$.getJSON('http://www.example.com/get_result.php', { id: 1 }, function(data) {
      $.each(data, function(value, name) {
          $('#selectField').append('<option value="' + value + '">' + name + '</option>');
      }
)};

What I'm looking for is either a better what of doing either of these or an extension (either library or a chunk of code) to jQuery that will do these without having to recreate the code all the time. Or is there already something in jQuery that makes this faster?

Edit: As mentioned by Kevin Gorski, populating the HTML element could be done as:

$('#elementId').load('http://www.example.com/get_result.php', { id: 1 });

This is perfect. Although, if you wanted to do a POST, it wouldn't work. Then doing Collin Allen's method is better.

+1  A: 

For filling an element with the results of an AJAH call, check out the load method.

I'm not aware of an existing plugin to specifically load JSON data into a select list, but it would be straightforward enough to write one.

Kevin Gorski
+3  A: 

Here's a quick jQuery plugin I wrote that makes your first example more re-usable:

(function ($) {
    $.fn.populateWith = function(sUrl, oData, fCallback) {
        if (!oData) oData = false;
        if (!fCallback) fCallback = false;
        $(this).load(sUrl, oData, fCallback);
    };
})(jQuery);

You target a <select> element (or group of elements, depending on your jQuery selector) and simply load in a given result from a backend like so:

$("#firstSelect").populateWith("backend.html");

Or, with a callback that gets fired after the load is done:

$("#secondSelect").populateWith("backend.html", false, function() {
    alert('Callback fired!');
});

Or, with callback and passed data:

$("#thirdSelect").populateWith("backend.html", {id: 1}, function() {
    alert('Callback fired with data!');
});

You can also call it with a data object and no callback, but you get the idea! Basically, this little plugin lets you worry about what options you want and where you want them, without fiddling with the details on the client-side. Output from the server side is expected to be plain HTML, but it could be easily adapted to handle any preferred format.

Hope this helps!

Collin Allen