jQuery populate items into a Select using jQuery ajax json, php

jQuery populate items into a Select using jQuery ajax json, php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Populating Select Dropdowns via AJAX in CodeIgniter and jQuery

Populating a <select> element dynamically is a common requirement when building web applications that rely on hierarchical data, such as categories and subcategories. The core workflow involves sending an identifier from the client side to a backend controller, retrieving related records from the database, and injecting the resulting HTML options into the DOM. While the foundational pattern remains consistent across frameworks, the implementation details differ significantly between CodeIgniter and modern Laravel ecosystems.

Structuring the PHP Response

In the provided source material, the PHP code returns a flat JSON structure containing a single result key. This approach is functional for simple data retrieval but insufficient for building HTML options. To render a <select> dropdown correctly, the backend must return an array of objects or arrays where each item contains distinct properties, typically id and name.

Consider this scenario: you receive a category_id via a POST request. The server needs to query the database for subcategories belonging to that parent ID. The response structure should look like this in JSON:

{
    "data": [
        { "id": 10, "name": "Electronics" },
        { "id": 11, "name": "Computers" }
    ]
}

Returning a flat string or a single value inside result prevents the client from iterating over the items to build <option> tags. The JSON structure must explicitly define the collection of options. If you are using CodeIgniter, ensure your controller method echoes this encoded array directly, rather than trying to parse strings on the client side.

Constructing the jQuery Request

The jQuery $.post call in the example passes the category ID in the data object. This is correct for POST requests, which are generally preferred when submitting forms or handling state-changing operations like loading specific sub-views. However, a critical detail often missed is the format of the success callback.

In the original snippet, alert(data.result) confirms receipt but does nothing with the data. To populate the dropdown, you must decode the JSON response and iterate through the array to generate HTML. You can use jQuery's .each() method or modern array methods like .map() depending on your library version.

$.post(base_url() + 'index.php/rubro/list_ajax/', { 
    idcategory: idc 
}, function(data) {
    // data is already a JSON object if dataType was set to 'json'
    var optionsHtml = '';
    
    // Safeguard against null responses
    if (data && data.data) {
        $.each(data.data, function(index, item) {
            // Escape HTML entities to prevent XSS if names come from the DB
            var safeName = $('<div>').text(item.name).html(); 
            optionsHtml += '<option value="' + item.id + '">' + safeName + '</option>';
        });
        
        $('#mySelect').html(optionsHtml);
    } else {
        console.warn('No data returned from server');
    }
}, 'json');

Note the use of dataType: 'json' in the .post() call. This instructs jQuery to automatically parse the response text into a JavaScript object before passing it to the callback function. Without this, data arrives as a string, and you would need to manually run JSON.parse(), which is error-prone if the server sends malformed JSON or an empty string.

Security and Best Practices in Dynamic Dropdowns

When building options dynamically, security becomes paramount. The source code example relies heavily on injecting data directly into the DOM. If the database contains malicious scripts in the name column of your subcategories table, rendering them directly causes Cross-Site Scripting (XSS).

Always sanitize output when constructing HTML strings. In jQuery, wrapping a string inside a temporary element like <div> and reading its .html() property strips tags but preserves text, effectively neutralizing script injections. Alternatively, use server-side escaping functions provided by your framework before echoing the JSON, ensuring the data sent to the client is already safe.

If you are migrating from CodeIgniter to a Laravel-based architecture, this pattern translates well but benefits from stricter type hints and validation middleware. The underlying logic of fetching sub-records and encoding them remains identical, but Laravel's response()->json() helper offers more robust error handling compared to raw echo json_encode().

The final step is verifying that the DOM element you are targeting exists before attempting to inject content. If the <select> field is rendered asynchronously elsewhere or manipulated by other scripts, ensure your jQuery selector matches the current state of the document.

Our network