Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way or reusable code to populate an HTML element or create a select after a jQuery AJAX call
    primarykey
    data
    text
    <p>I find myself doing 2 things quite often in JS, at the moment using jQuery:</p> <p>The first is the populating of an HTML element, which might look like:</p> <pre><code>$.get('http://www.example.com/get_result.php', { id: 1 }, function (data) { $('#elementId').html(data); }); </code></pre> <p>The second is populating a select element with a JSON result, such as:</p> <pre><code>$.getJSON('http://www.example.com/get_result.php', { id: 1 }, function(data) { $.each(data, function(value, name) { $('#selectField').append('&lt;option value="' + value + '"&gt;' + name + '&lt;/option&gt;'); } )}; </code></pre> <p>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?</p> <p><strong>Edit:</strong> As mentioned by <a href="https://stackoverflow.com/questions/365699/better-way-or-reusable-code-to-populate-an-html-element-or-create-a-select-afte#365790">Kevin Gorski</a>, populating the HTML element could be done as:</p> <pre><code>$('#elementId').load('http://www.example.com/get_result.php', { id: 1 }); </code></pre> <p>This is perfect. Although, if you wanted to do a POST, it wouldn't work. Then doing <a href="https://stackoverflow.com/questions/365699/better-way-or-reusable-code-to-populate-an-html-element-or-create-a-select-afte#365797">Collin Allen's</a> method is better.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload