Ivan
Ivan

Reputation: 5248

Append <options> to <select> using AJAX & PHP

I have two tables in my database:

1. Animal types 2. Breeds

animal_type:

type_id  |    name
------------------------
1        |  Dog
2        |  Cat
3        |  etc...

breed

ID   |  type_id |  name 
---------------------------
1    |    1     | Labrador
2    |    1     | Putbull
3    |    2     | Persian
etc.....

On my front page I want to show select dropdown menu with animal types and breeds select based on animal type.

1. Select animal type

<select id="animal_type">
   <option value="<?php $type->id">Dog</option>
   <option value="<?php $type->id">Cat</option>
</select>

2. If user select type undisable select list with breeds based on type

<!-- user select Dog type!  fetch all dog breeds -->
<select id="breeds" disabled>
   <option value="<?php $type->id">Labrador</option>
   <option value="<?php $type->id">Pitbull</option>
</select>

So I want to load all breeds from my controller based on witch type is selected. I try to slove this with ajax but am not realy good with him. I try this and dont know how to append new option to select dropdown.

Script :

$(document).ready(function() {

   // $("#breeds").attr('disabled', true);

    // check if selected
    if($("#animal_type").find('option:selected').val() == 0) {
        $("#breeds").attr('disabled', true);
    }

    $('#animal_type').change(function(){
        // get value of selected animal type
        var selected_animal_type = $(this).find('option:selected').val();

        $.ajax({
            url : "url-to-site/index.php/account/getBreedsByTypeID/1",
            type:'POST',
            dataType: 'json',
            success: function(response) {
                $("#breeds").attr('disabled', false);

                //alert(response); // show [object, Object]

                var $select = $('#breeds');

                $select.find('option').remove();
                $.each(response,function(key, value)
                {
                    $select.append('<option value=' + key + '>' + value + '</option>'); // return empty
                });
             }
        });
    });
 });

JSON returns my custom breed names

[{"breed_name":"Nema\u010dki prepeli\u010dar"},{"breed_name":"Irski vodeni \u0161panijel"},{"breed_name":"Barbe (Barbet)"},{"breed_name":"Lagoto 
My controller `mysite.com/index.php/account/getBreedsByTypeID/1`

This url returns the following encoded JSON

$breeds = $this->animal_breed->findAllBreedsByType($id); // Model @return array

return json_encode($breeds);

So how can I append that result to my select based on type?

Could you offer an example to solve this problem? Thanks.

Upvotes: 3

Views: 32455

Answers (3)

unbuntry
unbuntry

Reputation: 11

$("#departmentId").change(function() {
  console.log($("#departmentId").children("option:selected").val());
  console.log(getAllOfficeByDepartmentId($("#departmentId").children("option:selected").val()));
});

function getAllOfficeByDepartmentId(id) {
  $.ajax({
    type: 'GET',
    url: "getofficebydepartment/" + id,
    dataType: 'json',
    success: function (response) {
      console.log(response);
      $("#officeId").find('option').remove();
      $("#officeId").append('<option value="-1" selected>Select Office Name</option>');
      $.each(response, function (key, value) {
        $("#officeId").append('<option value="'+ value.officeId+'">' + value.officeName+'</option>');
      });
    },
    error: function (err) {
      alert("Error" + err);
    }
  });
}

*Compare with yours.

Upvotes: 0

$.ajax({
        url : "url-to-site/index.php/account/getBreedsByTypeID/1",
      data:{id:selected_animal_type},             
        type:'POST',
        dataType: 'json',
        success: function(response) {
            $("#breeds").attr('disabled', false);
            $.each(response,function(key, value)
            {
                $("#breeds").append('<option value=' + key + '>' + value.breed_name + '</option>');
            });
         }
    });

Upvotes: 2

Mahesh Jagdale
Mahesh Jagdale

Reputation: 174

$.ajax({
            url : "url-to-site/index.php/account/getBreedsByTypeID/1",
            type:'POST',
            dataType: 'json',
            success: function(response) {
                $("#breeds").attr('disabled', false);
                $.each(response,function(key, value)
                {
                    $("#breeds").append('<option value=' + key + '>' + value + '</option>');
                });
             }
        });

Upvotes: 8

Related Questions