skip to Main Content

My problem is when I inserted or updated a value, this code is not working but the status code in my network shows 200 means its OK

I want to fetch any data inside tbody section, where I fetch all of my data

This is my entire code

This is my HTML code where my table goes here after the page reload

        <!-- Table starts -->
        <div class="container-fluid">
            <table class="table table-hover table-responsive">
                <thead class="table-head">
                    <tr>
                        <th>Action</th>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Password</th>
                        <th>Birthday</th>
                        <th>Age</th>
                        <th>Mobile #</th>
                        <th>Address</th>
                        <th>Gender</th>
                        <th>Nickname</th>
                        <th>Occupation</th>
                    </tr>
                </thead>

                <tbody class="tbody">
                </tbody>
            </table>
        </div>
        <!-- Table ends -->

This is my code inside my script I am using jquery ajax to perform it.

    //view existing data
    function viewData(){
        $.ajax({
            method: 'POST',
            url: 'server.php',
            dataType: 'text',
            data: {
                key: 'viewData',
            },
            success: function(response){

                //this is my problem
                $('.tbody').append(response);

                //After I changed the append to html it works OMG!
                //just like this
                $('.tbody').html(response);

                $(".table").DataTable();
            }
        });
    }


//Insert data
    function manageData(key){
        var username = $('#username');
        var password = $('#password');
        var birthday = $('#birthday');
        var age = $('#age');
        var mobileNumber = $('#mobile-number');
        var fullAddress = $('#full-address');
        var gender = $('#gender');
        var nickname = $('#nickname');
        var occupation = $('#occupation');
        var editRowID = $('#editRowID');
        var query = window.location.search;

        if(isNotEmpty(username) && isNotEmpty(password) && isNotEmpty(birthday)
        && isNotEmpty(age) && isNotEmpty(mobileNumber) && isNotEmpty(fullAddress) 
        && isNotEmpty(gender) && isNotEmpty(nickname) && isNotEmpty(occupation)){
            $.ajax({
                method: 'POST',
                url: query + '/Dental-Clinic/admin/server.php',
                dataType: 'text',
                data: {
                    key: key,
                    username: username.val(),
                    password: password.val(),
                    birthday: birthday.val(),
                    age: age.val(),
                    mobileNumber: mobileNumber.val(),
                    fullAddress: fullAddress.val(),
                    gender: gender.val(),
                    nickname: nickname.val(),
                    occupation: occupation.val(),
                    rowID: editRowID.val()
                },
                success: function(response){
                    username.val(""),
                    password.val(""),
                    birthday.val(""),
                    age.val(""),
                    mobileNumber.val(""),
                    fullAddress.val(""),
                    gender.val(""),
                    nickname.val(""),
                    occupation.val(""),        
                    $(".modal").modal('hide');
                    viewData();
                }
            });
        }
    }

And this is my server.php

 //view/refresh data when new record has been saved

if(isset($_POST['key'])){
    if($_POST['key'] == 'viewData'){

        $query = "SELECT * FROM patient_table";
        $result = $connection->query($query);

        if ($result->num_rows > 0){
            $response = '';
            // output data of each row
            while($row = $result->fetch_array()) {
                $response .='
                    <tr>
                        <td class="d-flex justify-content-between"> <!--To align the button-->
                            <button class="btn btn-primary" onclick="edit('.$row["id"].')" id="edit" value="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-danger" id="delete"><i class="fas fa-trash-alt"></i></button>
                        </td>
                        <td>'.$row["id"].'</td>
                        <td>'.$row["username"].'</td>
                        <td>'.$row["password"].'</td>
                        <td>'.$row["birthday"].'</td>
                        <td>'.$row["age"].'</td>
                        <td>'.$row["mobile_number"].'</td>
                        <td>'.$row["full_address"].'</td>
                        <td>'.$row["gender"].'</td>
                        <td>'.$row["nickname"].'</td>
                        <td>'.$row["occupation"].'</td>
                    </tr>
                ';
            }
            echo($response);

        } else
            exit('no data');
    }
}


    //Insert data
    $username = $connection->real_escape_string($_POST['username']);
    $password = $connection->real_escape_string($_POST['password']);
    $birthday = $connection->real_escape_string($_POST['birthday']);
    $age = $connection->real_escape_string($_POST['age']);
    $mobileNumber = $connection->real_escape_string($_POST['mobileNumber']);
    $fullAddress = $connection->real_escape_string($_POST['fullAddress']);
    $gender = $connection->real_escape_string($_POST['gender']);
    $nickname = $connection->real_escape_string($_POST['nickname']);
    $occupation = $connection->real_escape_string($_POST['occupation']);
    $rowID = $connection->real_escape_string($_POST['rowID']);

    //add new data when manageData('addNew'); btn is clicked
    if($_POST['key'] == 'addNew'){
        $query = "INSERT INTO patient_table (username, password, birthday, age, mobile_number, full_address, gender, nickname, occupation) VALUES ('$username', '$password', '$birthday', '$age', '$mobileNumber', '$fullAddress', '$gender', '$nickname', '$occupation')";
        $result = $connection->query($query);
        if ($result) {
            echo '<script>alert("Successfully Inserted");</script>';
        } else {
            echo "Error: " . $query . "<br>" . $connection->error;
            exit("Error connecting to the database");
        }
    }

2

Answers


  1. Here i am Suppose that like this you have an insert code:-

    HTML Code:-

    <form id="FORM_ID" method="post">
        <input type="text" name="name" id="name"/>
        <input type="submit" name="submit" value="Insert" />
    </form>
    

    jQuery Ajax Code:-

    <script>
      $("#FORM_ID").submit(function() {
                    var name= $("#name").val();
                   
                    $.ajax({
                        type: "POST",
                        url: "insert.php",
                        data: "name=" + name,
                        success: function(data) {
                           function viewData();   // here call your viewData()
                              name.val("");  
                        }
                    });
                });
    </script>
    
    Login or Signup to reply.
  2. HTML

    <!-- Table starts -->
    <div class="container-fluid">
        <table class="table table-hover table-responsive" id="allData">
            <thead class="table-head">
                <tr>
                    <th>Action</th>
                    <th>ID</th>
                    <th>Username</th>
                    <th>Password</th>
                    <th>Birthday</th>
                    <th>Age</th>
                    <th>Mobile #</th>
                    <th>Address</th>
                    <th>Gender</th>
                    <th>Nickname</th>
                    <th>Occupation</th>
                </tr>
            </thead>
            <tbody class="tbody" id="viewdata">
            </tbody>
        </table>
    </div>
    <!-- Table ends -->
    

    JS

    function viewData(){
           var html = "<tr>";
            $.ajax({
                method: 'POST',
                url: 'server.php?apicall=fetch_all',
                type: 'POST',
                cache: false,
                success: function(response){
                    var parsedResponse = JSON.parse(response);
                    if(parsedResponse['error']=== false){
                         $.each(parsedResponse['details'],function(index,item){
                            html += "<td>"+item.id+"</td>";
                            html += "<td>"+item.username+"</td>";
                            html += "<td>"+item.password+"</td>";
                            html += "<td>"+item.email+"</td>";
                            html += "<td>"+item.birthday+"</td>";
    
                            html += '<td><a href="#" class="btn btn-primary edit" id=' + item.id+ '><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn btn-danger delete_item" id=' + item.id+ '><i class="fa fa-trash"></i></a></td>';
                            html += "</tr>";
                            $("#viewdata").html(html);
                        });
                    }
                                        }
                }).done(function (data) {
            $('#allData').DataTable();
        });;
    }
    
     $(document).ready(function(){
       viewData(); 
       $('form').submit(function(e){
            e.preventDefault();
            var formdata = new FormData(this);
            $.ajax({
            method: 'POST',
                url: 'server.php?apicall=add_new',
                type: 'POST',
                data: formData,
                processData: false,
                cache: false,
                success: function(response){
                    var parseresponse = JSON.parse(response);
                    if(response["error"] === false && response["message"] === "success"){
                        alert("success");
                    }else{
                        alert("Error");
                    }
                }
            }).done(function (data) {
                $('#allData').DataTable();
            });
        });
    });
    

    server.php

    $response = array();
    
    if (isset($_GET['apicall'])) {
        switch ($_GET['apicall']) {
            case 'fetch_all':
                    $details = array();
                    $sql= mysqli_query(conn, query); 
                    if($sql){
                        while($rec= mysqli_fetch_array($sql) ){
                            array_push($details, $rec);
                        }
                        $response['error'] = false;
                        $response['message'] = 'has data';
                        $response['details'] = $details;
                    }else{
                        $response['error'] = true;
                        $response['message'] = 'Error Occured';
                    }
                break;
            case 'add_new':
                    $username = $connection->real_escape_string($_POST['username']);
                    $password = $connection->real_escape_string($_POST['password']);
                    $birthday = $connection->real_escape_string($_POST['birthday']);
                    $age = $connection->real_escape_string($_POST['age']);
                    $mobileNumber = $connection->real_escape_string($_POST['mobileNumber']);
                    $fullAddress = $connection->real_escape_string($_POST['fullAddress']);
                    $gender = $connection->real_escape_string($_POST['gender']);
                    $nickname = $connection->real_escape_string($_POST['nickname']);
                    $occupation = $connection->real_escape_string($_POST['occupation']);
                    $sql= mysqli_query(conn, query); 
                    if($sql){
                        $response['error'] = false;
                        $response['message'] = 'success';
                    }else{
                        $response['error'] = true;
                        $response['message'] = 'Error Occured';
                    }
                break;
            default:
                $response['error'] = true; 
                $response['message'] = 'Invalid Operation Called';
                break;
        }
    }else{
        $response['error'] = true; 
        $response['message'] = 'Invalid API Call';
    }
    echo json_encode($response);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search