An illegal choice has been detected. Please contact the site administrator is given on ajax form after programmaticly adding an item to a select list I have a form in Drupal. On a select list I am using the ajax built into the form api to trigger a callback on change.

I need to be able to add an option to the select list via javascript. Set the value on the select list to be that new value and then trigger the ajax call.

I have something like:

var select_list = $('#edit-example');

select_list.append($("&lt;option&gt;&lt;/option&gt;")
  .attr("value", data.ObjectID)
  .text(data.Name));
select_list.val(data.ObjectID);
select_list.change();


Where data is a JSON object.

So the option is being added to the select list. The value has changed to my new option. I trigger the ajax event. However I am getting the error message:


  An illegal choice has been detected. Please contact the site administrator.


The callback is working fine except the error is displayed. What can I do to stop this message appearing?
Upon validation, the FAPI checks that the values given for any select/option/radios match what was originally available when the form was first built. This is a security check, and is built in to all form processing.

Changing the values of an existing select list with javascript means your form has been altered outside of Drupal's control (perhaps maliciously, the FAPI cannot know), and so the validation fails.

To stop the message appearing, you should use the AJAX framework to build you form, instead of manipulating it directly with jQuery.