bikey77
bikey77

Reputation: 6672

Dynamically add options to select with ajax

I'm trying to dynamically add options to a box using PHP, jQuery and AJAX.

First, a call to AJAX when the first control (taglist) is changed:

$('#taglist').change(function(){
    $.post('../includes/ajax.php', {   
      taglist:$(this).find("option:selected").attr('value')}, function(data) {
      $("#catlist").html(data.catlist);
    });
});

A PHP function fillselecteditmultiple() I've written populates a sting of the following format:

$options = '<option value="1">Option 1</option><option value="2">Option 2</option><option value="3">Option 3</option>';

which I return it to the page using json_encode like this:

if(isset($_POST['taglist'])){
    $catresult = mysql_query("select catid from category_tags where id='".$_POST['taglist']."'");
    $rowcat = mysql_fetch_array($catresult);

    $catlist = '<select name="cat_id[]" size="5" multiple id="cat_id[]">';
    $catlist .= fillselecteditmultiple(1, 0, $rowcat['catid']);
    $catlist .= '</select>';
    echo json_encode(array("status"=>"success", "catlist" => $catlist));
}

I need to return that string ($catlist) inside of a <select id="mylist"></select> accordingly so that the final output is this:

<select id="mylist">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

In Firebug I see the response correctly but nothing shown in the page.

How should I do this? Please ask for any clarifications if you feel thet my question is incomplete.

Upvotes: 0

Views: 9205

Answers (3)

Tim Joyce
Tim Joyce

Reputation: 4517

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
   //Relevant code
    $('#mylist').html(data);
  }
});

Upvotes: 1

SwiftD
SwiftD

Reputation: 6069

If you have jquery lib running do something like this:

$.ajax({
  url: 'your_script_url.php',
  success: function(data) {
    $('#mylist').html(data);
  }
});

alternatively you could append the data if you wanted to add extra options

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Use .append to insert contents inside an element. See below,

$('#mylist').append($options);

Upvotes: 1

Related Questions