0

My html:

<p id="book_no"><select name="books" id="bno" onclick="get_books()">
</select>&ensp;<i class="fa fa-solid fa-plus" style="cursor: pointer;" onclick="add_book()"></i></p>

My javascript:

function get_books(){
    let $select = $("#bno");
    return $.ajax({
        url: '/edit_qrtr/server.php',
        type: 'POST',
        data:{"input": "get_books"},
        dataType: 'json',
        success: function(response) {
            let selectedValue = $select.val();
            let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
            $select.html(html).val(selectedValue);
        },
        complete: function() {}
    });
}

function add_book(){
    get_books().done(() =>{
        let $select = $("#bno");
        let b = prompt("Please enter the new book no");
        if(b!=null)
            $select.append(`<option value="${b}">${b}</option>`);       
    })
}

The issue is that, when I try to add a new book, it doesn't get inserted into the list. How do I fix this issue? Please help me.

EDIT: In the function get_books(), I am fetching all the book nos that are already there in my sql table. In the second function add_book(), I am trying to add a new book no, which is not present in the already-fetched list of books.

  • 1
    Have a look at this [fiddle](https://jsfiddle.net/uz851ey7/). Your *add_book* method works. The problem might be, that you expect your *get_books* call to be finished when you select all options in your *add_book* method. Ajax is asynchronous! – Lapskaus May 18 '22 at 07:51
  • Change get_books() to `return $.ajax(...` then in your add_book code: `get_books().done(() => { ...rest of code that uses the result })` – freedomn-m May 18 '22 at 08:04
  • I've tried your suggestion, but the new value still doesn't get appended to the dropdown list. –  May 18 '22 at 09:08

0 Answers0