Hi,
I have a Book Registration Form, in which one book may have more than one authors and can belong to more than one category, therefore on the registration form, I have a textbox for the category, in order the category is not in the dropdown, I want to add that textbox value into the drop down box and the same thing for the author.

I did this, but when I refresh the page, the new category and author appears in drop down box, but I want without page refreshing.

see the attachment for more info, any idea?

Dani AI

Generated

— the behaviour you describe (new items only visible after a refresh) usually means the database insert is working but the page DOM is never updated. The easiest and most robust approach is: save the new category/author via AJAX, and on success immediately add an <option> to the select in the page DOM so the user sees it without reloading.

A minimal pattern to follow:

  • prevent the form from doing a normal submit,
  • read and validate the textbox value (trim, non-empty, no duplicates),
  • POST it to the server with AJAX,
  • on success, append a safe option node to the select and optionally select it.

Example jQuery flow:

$('#addCategoryBtn').on('click', function(e){
  e.preventDefault();
  var label = $.trim($('#newCategory').val());
  if (!label) return;
  if ($('#categorySelect option').filter(function(){ return $(this).text() === label; }).length) return;
  $.post('/addCategory', { name: label }, function(res){
    // assume res.id contains the new category id
    if (res && res.id) {
      var opt = $('<option/>').val(res.id).text(label);
      $('#categorySelect').append(opt).val(res.id);
      $('#newCategory').val('');
    } else {
      console.log('Save failed', res);
    }
  }, 'json');
});

Troubleshooting tips: check the Network panel to confirm the AJAX call and JSON response; ensure the server returns the new record id (or full record) so you can set the value; use $('select').append($('<option/>')...) to avoid HTML injection; prevent default form submission or ensure button type is not causing a reload. If you bind handlers to elements created later, use delegated events with .on().

For reference on the DOM methods used, see jQuery .append(), jQuery .val(), and jQuery.post().

my code is working, but when I refresh the page the new added data appears in drop down, this is the problem... any idea

any idea please ...

Sorry posting again,
If my problem is not clear, please give feedback and ask

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.