Updating a dropdown select in jQuery using AJAX and returning an empty string when it changes

Could someone please help me figure out what I am doing wrong here? When I use console.log(), it is returning an empty string instead of an array.

I am trying to update the second select box when the onChange event is triggered on the first select box, but I am unable to retrieve the data. When I use var_dump($results), it successfully displays an array of items, but when I use return $results, it gives me an empty string.

This is how the code looks like:

Here is the JavaScript function:

function _getNestedSelectOptions(activeComponent){
    $.ajax({
        type:   "POST",
        url:    "/backend/categories/get_nested_options/" + activeComponent
    }).done(function(html){
        console.log(html);
    });
}

And this is the PHP code in

controllers/backend/categories.php
:

public function get_nested_options($cid = FALSE){
    if($cid == FALSE)
        $cid = $this->activeComponent;

    $categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);

    $categoriesDropdownOptions = array();

    $this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);

    var_dump($categoriesDropdownOptions); // <-- THIS WORKS AND SHOWS AN ARRAY OF ITEMS
    //return $categoriesDropdownOptions; // <-- THIS DOES NOT WORKING
}

Here is the output on console.log():

array (size=3)
7 => string 'Administrators' ->(length=14)
8 => string 'Managers' ->(length=8)
9 => string 'Users' ->(length=5)

Answer №1

If you want to retrieve JSON using JavaScript, follow these steps:

Within the controller file:

public function fetchJsonData($categoryID = FALSE){
    if($categoryID == FALSE)
        $categoryID = $this->selectedCategory;

    $categoriesResponse = $this->categories_model->fetch_category_tree_by_id($categoryID);
    $jsonOptions = array();
    $this->categories_model->getNestedJsonOptions($jsonOptions, categoriesResponse);
     echo json_encode($jsonOptions); exit;
}



$.ajax({
  dataType: "json",
  type:   "POST",
  url:    "/backend/categories/fetch_json_data/" + selectedCategory
  data: jsonData  
}).done(function(data){
    jsonResponse = jQuery.parseJSON(data);
    console.log(jsonResponse);
}); 

You will receive the data in JSON format.

Answer №2

I was able to figure it out with the assistance of @KA_lin (jQuery.parseJSON() wasn't working, not sure why) and @RameshMhetre, so a big thank you to both of you for your help.

Here is an AJAX snippet in categories.js:

function _getNestedSelectOptions(activeComponent, targetName){
    // URL formatted in proper JSON format with data
    var url = "/backend/categories/get_nested_options/";
    // Target select box for applying modifications
    var ddb = $(targetName);
    // Save initial dummy/null option
    var top = ddb.find('option:first');
    $.ajax({
        type: 'POST',
        url: url + activeComponent,
        dataType: 'json',
        beforeSend: function(){
            // Disable select box
            ddb.prop('disabled', true);
        },
        success: function(data){
            // Insert saved initial dummy/null option
            ddb.empty().append(top);
            $.each(data, function (index, value) {
                // Append HTML data to target dropdown element
                ddb.append('<option val="'+ value.id +'">'+ value.title +'</option>');
            });
            // Re-enable select box
            ddb.prop('disabled', false);
        }
    });
}

controllers/backend/categories.php
:

public function get_nested_options($cid = FALSE){
    if($cid == FALSE)
        $cid = $this->activeComponent;

    // Get an array of properly structured parents and children
    $categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);

    // Prepare an array of dropdown option values (without keys)
    $categoriesDropdownOptions = array();

    // Populate array with appropriate values for use with form_dropdown($array)
    $this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);

    // Prepare an array for JSON output (with keys)
    $results = array();

    // Modify raw array with specific keys for JSON use
    foreach($categoriesDropdownOptions as $id => $title){
        $results[] = array(
            'id' => $id,
            'title' => $title
        );
    }

    // Set proper page content and output JSON results
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($results));
}

Lastly, in

views/backend/categories/form.php
:

<fieldset>
    <legend>Attributes</legend>
    <label class="control-label" for="formCatCid">
        Component name:
        <div class="controls">
            <?php
                $componentDropdownExtra = 'class="span12" onChange="categories.getNestedSelectOptions(this.value, formCatPid);"';
                echo form_dropdown('formCatCid', $componentDropdownOptions, set_value('formCatCid', $formCatCid), $componentDropdownExtra);
            ?>
        </div>
    </label>
    <label class="control-label" for="formCatPid">
        Category parent:
        <div class="controls">
            <?php
                $categoriesDropdownExtra    = 'class="span12"';
                echo form_dropdown('formCatPid', $categoriesDropdownOptions, set_value('formCatPid', $formCatPid), $categoriesDropdownExtra);
            ?>
        </div>
    </label>
</fieldset>

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

Secure Routes and Views with Laravel Package?

I've been creating a custom package specifically for Laravel 5.2 and I have reached the stage where I am integrating Authentication. I attempted to include an Auth folder in my resources/views directory, along with the necessary Controllers in my pac ...

Extracting and retrieving data using JavaScript from a URL

After reviewing some code, I am interested in implementing a similar structure. The original code snippet looks like this: htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' + items[i].name + '& ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Methods for verifying data in php (with the utilization of the GET method)

I am currently working on a project involving the use of Module SIM 808 and a web server. For transferring data to my website, I have utilized the GET method where the data is sent through the URL. Example: www.mywebsiteaddress/?data1=sensor1_value&d ...

Obtain data from a dynamic website using AJAX (XMLHttpRequest) in C#

I am working on developing a C# application to retrieve my data cap details from my ISP's website. The specific page I am refering to can be found here, however, I suspect that it may only be accessible within their network. If you require more inform ...

Ways to send information to browser javascript from Spring MVC controller

Looking for the most efficient method to transfer data from Spring MVC to JavaScript. Let's say there is an array in JavaScript: var myArray = new Array(); And in the Java backend, there is another array: int[] myArray = new int[100]; What would ...

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

Steps for increasing a specified time by a specific number of minutes and linking the updated time to an array list

I have a requirement to increase a given time by a specified number of minutes and link this new time with an array list of IDs. For example: $ids_arrays = array(699926900040821, 699926900040822, 699926900040823); $given_time='20:30'; $given_ ...

Guide to filtering an array within ag-grid when defining a column

After switching from using DataTable to ag-grid, I encountered a challenge. In DataTable, I accessed the first element from the attributes array where typeName='ItemType'. Now, I am looking to achieve the same functionality in ag-grid. Any sugges ...

Script for automated functions

I have implemented 4 functions to handle button clicks and div transitions. The goal is to hide certain divs and show one specific div when a button is clicked. Additionally, the background of the button should change upon hovering over it. Now, I am look ...

Experiencing an issue with Handsontable: Every time I try to run the countRows method, all I get is "undefined."

Greetings everyone! I appreciate you taking the time to read about my issue. I've been using the handsontable library for a week now and have encountered some difficulties with certain methods. Within a function, I have the following code: count = $ ...

The currentViewData property of the model is not defined, resulting in a TypeError when implementing the Hierarchical Grid and accessing the Child Grid

I'm currently working on implementing a Hierarchy Grid in ASP.Net MVC using Syncfusion Grid Control. During the process of fetching data from the server side with an ajax call for the expansion of the child grid, I encountered a JavaScript error (Type ...

Security Vulnerability in Ajax Callback Breakpoints

Imagine I have the following code snippet (partially pseudocode) $.ajax({ url: "/api/user", success: function(resp) { var data = JSON(resp) if (data.user.is_admin) // do admin thing else // do somet ...

Using CodeIgniter to select a value in a form dropdown

One issue I am currently facing is with a dropdown field in my form. Upon hitting submit, the form undergoes validation and if an error occurs, all the values are returned. This process works well for most fields except for my dropdown menu. Although I hav ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Pattern matching to locate text that is not enclosed within HTML tags and does not fall within certain specified tags

I am attempting to create a regular expression that will match specific words located outside and between HTML tags (but not within the tags themselves). However, I also need to ensure that these words are excluded when they appear between heading tags suc ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

Troubleshooting an Error with Ajax and PHP JSON Response

Having trouble with my website registration form. Getting 'null' as a response from the server when using json for data exchange. Here is the code: JavaScript code: $("#customer-form").submit(function() { var form_data = { c ...