0

Can someone tell me what I'am doing wrong here, console.log() returns me an empty string instead of an array ?

I want to update the second selectbox once onChange is triggered on first selectbox but I can't retrieve the data. When I'am doing a var_dump($results) it successfully shows an array of items, but return $results returns me an empty string.

Here how it looks like:
enter image description here

a javascript:

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

And this is a php code 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 an output on console.log():

array (size=3)
7 => string 'Administrators' ->(length=14)
8 => string 'Managers' ->(length=8)
9 => string 'Users' ->(length=5)
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95
  • Is it me or $categoriesDropdownOptions is an empty array...all the time? – ka_lin Dec 01 '13 at 22:50
  • I don't see a `data` block for your POST event – Machavity Dec 01 '13 at 22:51
  • Check if it is an ajax request and just send JSON data and replace dropdown elements – ka_lin Dec 01 '13 at 22:53
  • I don't get it guys, really sorry. I've updated my question by comment `return $categoriesDropdownOptions` and uncommenting `var_dump()` to show you an output what I get in `console.log()` – aspirinemaga Dec 01 '13 at 22:58
  • @KA_lin - nope, only when doing `return $categoriesDropdownOptions;` – aspirinemaga Dec 01 '13 at 23:05
  • 1
    use echo json_encode($categoriesDropdownOptions),delete all elements in dropdown, parse the response(http://api.jquery.com/jQuery.parseJSON/), iterate and append in dropdown(http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist-using-jquery) – ka_lin Dec 01 '13 at 23:14
  • will do and gives you my feedback, thank you – aspirinemaga Dec 01 '13 at 23:22
  • 1
    Instead 0of using simple ajax try using json :http://stackoverflow.com/questions/6325695/creating-json-data-using-php-and-parsing-it-using-jquery – Ramesh Mhetre Dec 02 '13 at 04:45

2 Answers2

1

You can try to get json in js, use

In controller:

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

    $categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
    $categoriesDropdownOptions = array();
    $this->categories_model->getNestedOptions($categoriesDropdownOptions, categoriesResult);
     echo json_encode($categoriesDropdownOptions); exit;
}



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

you will get data in json format.

Nish
  • 325
  • 2
  • 3
  • 11
  • I don't know why but either `jQuery.parseJSON()` and `$.parseJSON()` both are not working. But thanks for a tip – aspirinemaga Dec 02 '13 at 08:41
  • You checked response ? data is coming or not check before parse. – Nish Dec 02 '13 at 11:39
  • i got an error, telling undefined `jQuery.parseJSON()`, i don't know why I'am getting it. but i managed it in another way, pls check my own answer, i will leave it unaccepted until someone other will answer. thank you anyway @Nish – aspirinemaga Dec 02 '13 at 12:24
0

I managed to work it out by helps of @KA_lin (jQuery.parseJSON() didn't work, idk why) and @RameshMhetre, so thank you guys for your helps.

This is an AJAX in categories.js:

function _getNestedSelectOptions(activeComponent, targetName){
    // Url in proper JSON format with datas
    var url = "/backend/categories/get_nested_options/";
    // Target selectbox to apply modifications on it
    var ddb = $(targetName);
    // Save first dummy/null option
    var top = ddb.find('option:first');
    $.ajax({
        type: 'POST',
        url: url + activeComponent,
        dataType: 'json',
        beforeSend: function(){
            // Disable selectbox
            ddb.prop('disabled', true);
        },
        success: function(data){
            // Insert saved first 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 selectbox
            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 constructed parents and childs
    $categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);

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

    // Fill in an 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 a raw array with specific keys for use in JSON
    foreach($categoriesDropdownOptions as $id => $title){
        $results[] = array(
            'id' => $id,
            'title' => $title
        );
    }

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

And the 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>
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95