Add newly added record to select2 element

27 Views Asked by At

I have an add form, which adds a record in a table and get back the newly createdId of that record.

On the same page, I have another form which has a select2 element and I would like to perform the search automatically using the new createdId without to ask from the user to search in the select2 element. The goal is, as soon as I add the new record, second script to search for the data of that record and to display it in the select2 element.

I have this JavaScript:

    var createdId;
    // Ajax call to add new foreas or contact
    $('#add_form').submit(function (event) {
        // Prevent default form submission
        event.preventDefault();

        // Serialize form data
        var formData = $(this).serialize();

        // AJAX call
        $.ajax({
            type: 'POST',
            url: "<?php echo site_url('my/addContact');?>",
            data: formData,
            dataType: 'json',
            success: function (response) {
                // Handle the response from the server
                if (response.success) {
                    // Data insertion successful
                    createdId = response.created_id;
                } else {
                    // Data insertion failed
                    console.error('Failed to insert data: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred during AJAX request: ' + error);
            }
        });
    });

    console.log('Here, createdId is ' + createdId); // Id is printed in the console

    // Retrieve records from contacts
    $('.ajax-requests-select3').select2({
        language: {
            searching: function () {
                return "Searching...";
            },
            loadingMore: function () {
                return "Loading more results..."
            }
        },
        placeholder: "Select - Search",
        allowClear: true,
        ajax: {
            delay: 250,
            allowClear: true,
            url: '<?= base_url("contacts/search_contacts") ?>',
            dataType: 'json',
            cache: true,
            data: function (params) {
                var query = {
                    term: params.term || createdId, // <<< Here I am assigning the id
                    page: params.page || 1
                }
                return query;
            },
        }
    });

My question is: Is there any way that I could trigger the second script somehow to find the createdId?

In the network tab I can see only the first AJAX request, but second is never fired. I have spent many hours over this code and any help will be deeply appreciated.

0

There are 0 best solutions below