seularts 0 Light Poster

I have a very standard code where I use a CRUD interface on my Database. The issue is that every attempt I made to redraw/update the table with the new data [ $('.table').DataTable().draw(); ] has failed miserably. Here is my targeted code:

        function manageData(key) {
            var name = $("#countryName");
            var shortDesc = $("#shortDesc");
            var longDesc = $("#longDesc");
            var editRowID = $("#editRowID");

            if (isNotEmpty(name) && isNotEmpty(shortDesc) && isNotEmpty(longDesc)) {
                $.ajax({
                   url: 'ajax.php',
                   method: 'POST',
                   dataType: 'text',
                   data: {
                       key: key,
                       name: name.val(),
                       shortDesc: shortDesc.val(),
                       longDesc: longDesc.val(),
                       rowID: editRowID.val()
                   }, success: function (response) {
                       if (response != "success")
                           alert(response);
                       else {
                           $("#country_"+editRowID.val()).html(name.val());
                           name.val('');
                           shortDesc.val('');
                           longDesc.val('');
                           $("#tableManager").modal('hide');
                           $("#manageBtn").attr('value', 'Add').attr('onclick', "manageData('addNew')");
                           /* window.location.reload(); */
                           $('.table').DataTable().draw();

                       }
                   }
                });
            }
        }

This function adds, through a HTML Modal, a new entry in the database using this simple php condition:

if ($_POST['key'] == 'addNew') {
            $sql = $conn->query("SELECT id FROM country WHERE countryName = '$name'");
            if ($sql->num_rows > 0)
                exit("Country With This Name Already Exists!");
            else {
                $conn->query("INSERT INTO country (countryName, shortDesc, longDesc) 
                            VALUES ('$name', '$shortDesc', '$longDesc')");
                exit('success');
            }
        }

And this is how I display my code in the page:

        $(document).ready(function() {

            $("#addNew").on('click', function () {
               $("#tableManager").modal('show');
            });

            $("#tableManager").on('hidden.bs.modal', function () {
               $("#showContent").fadeOut();
               $("#editContent").fadeIn();
               $("#editRowID").val(0);
               $("#longDesc").val("");
               $("#shortDesc").val("");
               $("#countryName").val("");
               /* $("#closeBtn").fadeOut(); */
               $("#manageBtn").attr('value', 'Add New').attr('onclick', "manageData('addNew')").fadeIn();
            });

            getExistingData(0, 50);
        });

                function getExistingData(start, limit) {
            $.ajax({
                url: 'ajax.php',
                method: 'POST',
                dataType: 'text',
                data: {
                    key: 'getExistingData',
                    start: start,
                    limit: limit
                }, success: function (response) {
                    if (response != "reachedMax") {
                        $('tbody').append(response);
                        start += limit;
                        getExistingData(start, limit);
                    } else

                $('.table').DataTable({"order": [ 0, 'desc' ]}); $('#options').on( 'change', function () { $('.table').DataTable().column(1).search( this.value ).draw(); });

                }
            });
        }

        // PHP condition
        if ($_POST['key'] == 'getExistingData') {
            $start = $conn->real_escape_string($_POST['start']);
            $limit = $conn->real_escape_string($_POST['limit']);

            $sql = $conn->query("SELECT id, countryName FROM country ORDER BY id desc LIMIT $start, $limit");
            if ($sql->num_rows > 0) {
                $response = "";
                while($data = $sql->fetch_array()) {
                    $response .= '
                        <tr>
                            <td>'.$data["id"].'</td>
                            <td id="country_'.$data["id"].'">'.$data["countryName"].'</td>
                            <td>
                                <input type="button" onclick="viewORedit('.$data["id"].', \'edit\')" value="Edit" class="btn btn-primary">
                                <input type="button" onclick="viewORedit('.$data["id"].', \'view\')" value="View" class="btn">
                                <input type="button" onclick="deleteRow('.$data["id"].')" value="Delete" class="btn btn-danger">
                            </td>
                        </tr>
                    ';
                }
                exit($response);
            } else
                exit('reachedMax');
        }

Everything is poured into a simple Bootstrap Table. I looked all over the documentation of DataTables - https://datatables.net/reference/api/draw() but I can't seem to make the table to redraw itself after I add the new country! Trying to reuse getExistingData(0, 50); ends up in an error message of: Cannot reinitialise DataTable

The only useful condition is the draw() in the $('.table').DataTable().draw(); function but in this case it simply doesn't do anything in my code. This function does work as seen in: $('.table').DataTable().column(1).search( this.value ).draw(); where I redraw the table when searching a specific country!

Can anyone point me to the right answer please!?

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.