Populate dropdown list dynamically in Codeigniter using AJAX and jQuery

Although this question may appear to be a duplicate, none of the other answers provided have solved my issue.

My query pertains to populating a dropdown using ajax/jquery. While I can successfully send and receive data in JSON format, it doesn't seem to append to the dropdown. Here is my code:

View

<select name="guard_id" id="guard_id" style="width:100%;">
<option>select guard</option>
<optgroup label="Previously assigned guard" id="trained_guards">
</optgroup>
</select>

Jquery/Ajax call

function checkTrainedGuards(sid) {

$.ajax({
dataType: 'JSON',
type: 'POST',
url: '<?php print site_url('roster/check_trained_guards'); ?>',
data: { sid: sid},
beforeSend:function() {
$('#sid').addClass('loader-roster');
},
success:function(data) {
var appenddata;
$.each(data, function (key, value) {

appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";                        
});
$('#trained_guards').html(appenddata);

},
error:function(){
}
});
}

Controller

public function check_trained_guards(){

$this->load->model("guard");
$sid=$this->input->post("sid");

$trainedGuards=$this->guard->getGuardAlreadyWorkedOnSite($sid);

foreach ($trainedGuards as $guard) {

print json_encode(array(
'gid' => $guard->gid,
'gname' => $guard->guard_name
));
}
}
}

Upon testing with firebug, the data appears correct and in JSON format as displayed below:

[{"gid":"293","gname":"Abc"},{"gid":"96","gname":"guard2"},{"gid":"101","gname":"guard3"},{"gid":"91","gname":"guard4"}]

Despite this, the results are not being appended to the dropdown box. Additionally, when I tried alert(value.gid) within the jquery each loop, it returns undefined.

Any assistance on this matter would be greatly appreciated.

Answer №1

It appears that the structure of your JSON is incorrect. The PHP code should be structured as follows:

$arr = array();
foreach ($trainedGuards as $guard) {
    $arr[] = $guard;
}

print json_encode($arr);

After implementing this code, you will receive a valid JSON response containing an array of objects like the example below:

[{"gid":"2","gname":"Guard1"},{"gid":"3","gname":"Guard2"}]

In your AJAX response, use the following code snippet:

var data = [{"gid":"2","guard_name":"Guard1"},{"gid":"3","guard_name":"Guard2"}]; 
// This is the expected response format. You can also utilize JSON.parse if dealing with string format

var appenddata = "";
$.each(data, function (key, value) {

    appenddata += "<option value='" + value.gid + "'>" + value.gname + "</option>";                        
});
$('#trained_guards').html(appenddata);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance Wordpress search results by prioritizing pages containing specific keywords in the title

As a beginner in PHP, I am attempting to enhance the visibility of pages that contain specific words in their titles by ensuring they rank higher in search results. I made changes to this snippet /*Relevanssi sort boost exact matches in search results*/ ...

Querying a .json document for a specific item and showcasing its price with the help of Discord.js

My current goal is: User inputs !price (item) The bot will look up the item in a JSON file, for example: [ { "hi": 700000, "low": 650000, "name": "football" } ] The bot will then respond with Name: Football High: 6500 ...

Creating dynamic div containers on the fly

I'm dealing with an issue in my application where multiple overlapping div boxes are being dynamically generated and they all end up having the same content. When I add content to a box, it gets applied to all existing boxes instead of just the last o ...

Working with C++ to extract and store information from a map containing boost::any values in XML or JSON form

The map is declared as follows: std::map<const std::string,boost::any> data I am looking to create a function that can transfer all the data from the map to a file and another function that can read this data back in, initializing the map with the c ...

The function window.open() is experiencing difficulties when trying to open a file located in a subfolder

As someone who is new to programming, please excuse any lack of knowledge on my part, but I am having trouble finding the answer to this. I am currently using window.open() to open a .php file in a popup window and passing a variable through the URL to be ...

What is the best method for incorporating a query in Ajax code while also passing parameter data?

I am currently working on a project in Laravel that involves using a create form with AJAX. After the form is completed, I need to merge data from two tables together within the AJAX code so that I can make specific selections. Here is an example of the AJ ...

Issue with Loading DOCTYPE and HEAD Tags in PHP

I have made changes to my index page structure. $page is declared at the beginning and then different sections of the page (header, menu, body & footer) are updated later in the code. However, I am facing an issue where the DOCTYPE and data are not loadin ...

Searching with preg_match

<?php $content = " {php {php 1 php} {php 2 php} {php 3 php} php}"; How can I extract four separate strings? The first block: {php 1 php} {php 2 php} {php 3 php} The second one: 1 The third part: 2 And finally, the fourth piece: 3 ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Displaying the contents of an ArrayList in a Spring Boot application

After creating an ArrayList with the JSON values from a Rest API, I encountered the following code to read the Rest API: @RestController public class exemploclass { @RequestMapping(value="/vectors") ...

Tips for choosing specific elements of an array for pagination in php

If I have arrays structured like this: [0] => Array{ [name]=>ABC } [1] => Array{ [name]=>ABC } [2] => Array{ [name]=>ABC } [3] => Array{ [name]=>ABC } [4] => Array{ [name]=>ABC } [5] => Array{ [name]=>ABC } ...

Automatically Trigger Setup Upon Download Completion [PHP]

When you go to https://www.google.com/chrome/browser/#eula to download Google Chrome, the setup file starts automatically after clicking the accept & install button. I am wondering if it is possible for me to open a file on the user's pc in the same w ...

Using AngularJS to retrieve JSON data with the HTTP module

I am a beginner in the world of angularjs and I need some guidance. Below is the code I have written: <!DOCTYPE HTML> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>Angularjs project</title> <script type= ...

The JSON data was retrieved in a different order compared to the text data during scraping

Attempting to retrieve data from www.crunchbase.com through their API, I created a basic Python script for fetching responses. However, when writing the json_data to a file, I noticed that the order of the keys does not match the response order obtained di ...

What makes the string '592e5399' evaluate to TRUE when using the is_infinite() function?

<?php $number1 = 1; $number2 = 0; $result = $number1/$number2 ; The value of $result will be float(INF) which is not a valid number. var_dump($result); In order to check if $result is infinite, we can use the function is_infinite as shown below. $ ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

"Encountering an Unexpected Error with Flutter/Dart JSON

There seems to be a problem with handling Json in Dart. Future Search(String tags) async{ final response = await http.get(baseURL + tags + "&limit=100",headers: {"Accept": "text/html,application/xml"}); if (response.statusCode == 200) { ...

The unusual loading of images in TableSorter

While debugging my frontend on Chrome, I noticed a strange behavior with the TableSorter plugin when applied to a table on the page. It seems to be trying to load string/binary data from this URL (and generating at least 10 requests simultaneously): Reque ...

How do I add JSON data to a menu using PHP?

I have a JSON file for my menu structured like this: [{"slug":"index.php","name":"Home"},{"slug":"aboutus","name":"About us","children":[{"slug":"eims","name":"Eims"},{"slug":"vision","name":"Vision"}]},{"slug":"trash","name":"Trash","children":[{"slug":" ...

Transmit the Selected Options from the Checkbox Categories

Here's an intriguing situation for you. I've got a webpage that dynamically generates groups of checkboxes, and their names are unknown until they're created. These groups could be named anything from "type" to "profile", and there's a ...