I have been working this for a while and have found numerous clues here on SO, but nothing is working yet. I'm trying to create a dynamic drop down in a form that the user can add to by selecting an "add new" option which brings up a modal window in which the new option can be typed. I use jquery to bring up the window and capture the input and ajax to (hopefully) post the text and retrieve it in php. I see on the console that that the new option is captured in the javascript and ajax makes a post, but the post array is empty.
My code is all in the view. When an "add new" is selected a modal window pops up in which text can be entered. I want to capture the entered text in the view without submitting and display it in the updated options list.
<legend>Animal Info</legend>
<div class="control-group <?php if (form_error('animal_species')) { echo 'error'; } ?>">
<label class="control-label">Species</label>
<div class="controls">
<?php # Add "Add New"
$options = $species + array('addnew' => 'Add New');
echo form_dropdown('animal_species', $options,
set_value('animal_species', (isset($my_data->animal_species)) ? $my_data->animal_species: ''),
'id = "animal_species"',
'class', 'addnew');
echo form_error('animal_species', '<span class="help-inline">', '</span>');
?>
</div>
</div>
<?php
if(isset($new_option))
{
$new_option = $_POST['new_option'];
$species = array($new_option => $new_option) + $species;
var_dump($new_option);
}
?>
<script type="text/javascript">
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
$('#add-new-submit').on('click', function(){
// Get new option from text field
var new_option = $('#add-new-text').val();
console.log(new_option);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
data: {new_option:'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
$('#add-new').modal('toggle');
});
//});
});
</script>
<!-- add-new field -->
<div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="add-new-fieldLabel">Add New Field</h3>
</div>
<div class="modal-body">
<p>Would you like to add a new item?</p>
<input type="text" id="add-new-text" name="add-new" placeholder="Type the new option">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
</div>
</div><!-- /add-new field -->
Right now the string new_options gets captured in the console but is NULL in the php, so ajax isn't posting for some reason. Is this because I'm trying to update the same page?