• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dropdown with option of 'Add New' and save new item to DB

Hi, Sorry to ask this, as it is I'm sure covered SOMEWHERE, but I have been searching for the last hour and cannot seem to find a relevant posting.

I am populating a dropdown on a form based on a DB table (id, description). I'd like to offer an option of adding a new item while filling out the form so they don't have to stop, go to another screen, add a new item to table, and then start completing form again.

I also need this new item saved to the database (where the ID is auto generated) so that the proper ID can be saved to the main entry (we'll say customer info table).

I'm guessing this is done via AJAX and/or jQuery, but I am not really sure where to start. I do not know much about AJAX/jQuery yet, but if someone has a working example of this actual issue, PLLLLEEEAAASSSEEEE help me.

Thank you!!!!!!!!!!!!!!

[eluser]Victor Michnowicz[/eluser]
If you have some HTML in your page like this:

<form method="post" id="new_item_form" action="/welcome/add">
<input type="text" name="new_item" id="new_item" />
<input type="submit" value="Add New Item" />

Then put some jQuery in your page like:

$('#new_item_form').submit(function(e) {
$.post($(this).attr('action'), $(this).serialize(),
if (data == 'true') {
// Load new dropdowns
$('#div_around_my_dropdown').load('/welcome #div_around_my_dropdown', function() {
alert('Item Added');
else {
alert('ERROR: ' + data);

Then in the "welcome" controller add the "add" method:

public function add()
$new_item = trim($this->input->post('new_item'));

if ($new_item)
$data = array(
name => $new_item
$this->db->insert('my_table', $data);
echo 'true';
echo 'false';

I'm sure there are some errors in my code, but it should get you started. Basically we are using jQuery to jQuery.post() some data to our "add" method. This method inserts the user-inputed text into the database. The method then echos "true." jQuery then checks that our DB insert succeeded. If it worked, it then uses the .load() function to grab a newer version of the page (the one with the new option we just added).

There are tons of ways to skin this cat. Another way may is to return the insert ID from the database instead of just "true" or "false." We can then use this insert ID to add a new option to the select input. This would be an alternative to the .load() function (and may be a bit faster?)

$('#my_select_input').append('<option value="' + data + '">' + $(new_item).val() + '</option>');

If you wanted to get fancy you could look into json_encode() too.

Awesome, thank you for the direction. I think I can figure it out from there, but if I get stuck, will let you know. Thank you again!!

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.