Skip to content
Advertisement

when i click add, data is saved and also shown on the same page through ajax but if i want to sort data, button is not working

im adding data in the db and at the same time it is shown to the same page through ajax when add button is clicked. now i want to show data in ascending order adn as well as in descending order also. data is shown on add click but when i clicked ascending button, data is not shown. same is the thing with descending button.

add.php file

<section class="my-5">
    <div class="py-5">
        <h2 class="text-center">Information</h2>
    </div>

    <div class="w-50 m-auto">
        <form method="POST" onsubmit="event.preventDefault();onSubmit();"> 
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="title" id="title" autocomplete="off" class="form-control" required="">
            </div>

            <div class="form-group">
                <label>Description</label>
                <input type="text" name="description" id="description" autocomplete="off" class="form-control" required="">
            </div>
            <br>
            <button type="submit" class="btn btn-success" id="fetch" name="dataadd" onclick="addRecord();">Add</button>
            </div>
        </form>
    </div>
</section>

<section align="center"> 
    <form>
        <button type="submit" class="btn btn-success" name="ascd" onclick="ascdRecord();">Ascending</button>
        <button type="submit" class="btn btn-success" name="desc" onclick="descRecord();">Descending</button>
    </form>
</section>

<br>
<br>

    <div align="center">
        <h2 id="records">Show All Data</h2>
    </div>
</div>

The javascript functions

<script type="text/javascript">

function addRecord()
{
     var title = $('#title').val();
     var description = $('#description').val();

     $.ajax({
        url: "data.php",
        type: "POST",
        data: {
            title: title,
            description: description
        },
        success: function(data, status)
        {
            readRecords();
        }
     });
}

function readRecords()
{
    var readrecord = "readrecord";
    $.ajax({
        url: "data.php",
        type: "POST",
        data: {readrecord: readrecord},
        success: function(data, status)
        {
            $('#records').html(data);
        }
    });
}

function DeleteUser(deleteid)
{
    var conf = confirm("you want to delete ?");
    if (conf==true) {
    $.ajax({
        url: "data.php",
        type: "POST",
        data: {deleteid: deleteid},
        success: function(data, status)
        {
            readRecords();
        }
    });
    }
}

function ascdRecord()
{
    $("#ascd").click(function(){

    $.ajax({
        url: "data.php",
        type: "POST",
        dataType: "html",
        success: function(data)
        {
            $('#records').html(data);
        }
    });
    });

}
</script>

data.php file

if(isset($_POST['ascd']))
{
    echo "<div class='result'>";
    $data = '<table>

    <tr>
    <th>Title</th>
    <th>Description</th>
    </tr>

    ';

    $fetch_query = "select * from app.add order by title";
    $fetch_run = mysqli_query($con, $fetch_query);

    if(mysqli_num_rows($fetch_run) > 0)
    {
        while($row = mysqli_fetch_array($fetch_run))
        {
            $data .= '<tr style="border: 1px solid black; padding: 8px; text-align: center">

            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
            <td>
            <button onclick="DeleteUser('.$row['id'].')">Delete</button>
            </td>

            </tr>';
        }
    }
    $data .= '</table>';
    echo $data;

    echo "</div>";
}


if(isset($_POST['readrecord']))
{
    echo "<div class='result'>";
    $data = '<table>

    <tr>
    <th>Title</th>
    <th>Description</th>
    </tr>

    ';

    $fetch_query = "select * from app.add";
    $fetch_run = mysqli_query($con, $fetch_query);

    if(mysqli_num_rows($fetch_run) > 0)
    {
        while($row = mysqli_fetch_array($fetch_run))
        {
            $data .= '<tr style="border: 1px solid black; padding: 8px; text-align: center">

            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
            <td>
            <button onclick="DeleteUser('.$row['id'].')">Delete</button>
            </td>

            </tr>';
        }
    }
    $data .= '</table>';
    echo $data;

    echo "</div>";
}

if(isset($_POST['title']) && isset($_POST['description']))
{

    $insert_query = "insert into app.add (title, description) values('$title','$description')";
    $query_run = mysqli_query($con, $insert_query);

}

Advertisement

Answer

You can modify each function to send a new parameter – I chose task but that it not important. The value is changed for each request type as you will see in the javascript. The PHP code can look for and then fork logic based upon this single POST variable.

FYI: Blindly extracting variables in PHP using extract opens the door to various attacks – only use that with caution once you have sanitised the POST array ~ perhaps using filter_input_array as a start and a whitelist of acceptable names/types.

function addRecord(){
     var title = $('#title').val();
     var description = $('#description').val();

     $.ajax({
        url: "data.php",
        type: "POST",
        data: {
            task:'add',
            title:title,
            description:description
        },
        success: function(data, status)
        {
            readRecords();
        }
     });
}

function readRecords(){
    $.ajax({
        url: "data.php",
        type: "POST",
        data: {
            task:'read'
        },
        success: function(data, status)
        {
            $('#records').html(data);
        }
    });
}

function DeleteUser(deleteid){
    if( !confirm("you want to delete?") )return false;

    $.ajax({
        url: "data.php",
        type: "POST",
        data: {
            task:'delete',
            deleteid:deleteid
        },
        success: function(data, status)
        {
            readRecords();
        }
    });
    
}

function ascdRecord(e){
    $.ajax({
        url: "data.php",
        type: "POST",
        data:{
            task:'ascd'
        },
        dataType: "html",
        success: function(data)
        {
            $('#records').html(data);
        }
    });
}
/* presume similar for dscdRecord */
function descRecord(e){
    $.ajax({
        url: "data.php",
        type: "POST",
        data:{
            task:'dscd'
        },
        dataType: "html",
        success: function(data)
        {
            $('#records').html(data);
        }
    });
}

Data.php

if( isset( $_POST['task'] ) ){
    switch( $_POST['task'] ){
        case 'add':
            if(isset(
                $_POST['title'],
                $_POST['description']
            )){
                # this is prone to SQL injection - you should use a `Prepared statement`
                /*
                $insert_query = "insert into app.add () values('$title','$description')";
                $query_run = mysqli_query($con, $insert_query);
                */
                
                
                $sql='insert into `app`.`add` ( `title`, `description` ) values (?,?)';
                $stmt=$con->prepare($sql);
                $stmt->bind_param('ss',$_POST['title'],$_POST['description']);
                $stmt->execute();
                $stmt->close();
            }
            
        break;
        case 'delete':
        
        break;
        case 'read':
            
            $data = '
            <div class="result">
                <table>
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                    </tr>';

            $fetch_query = "select * from app.add";
            $fetch_run = mysqli_query($con, $fetch_query);

            if(mysqli_num_rows($fetch_run) > 0)
            {
                while($row = mysqli_fetch_array($fetch_run))
                {
                    $data .= '
                    <tr style="border: 1px solid black; padding: 8px; text-align: center">
                        <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
                        <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
                        <td>
                            <button onclick="DeleteUser('.$row['id'].')">Delete</button>
                        </td>
                    </tr>';
                }
            }
            $data .= '
                </table>
            </div>';
            
            header('Content-Type: text/html');
            exit( $data );
        break;
        case 'ascd':
            
            $data = '
            <div class="result">
                <table>
                    <tr>
                    <th>Title</th>
                    <th>Description</th>
                    </tr>';

            $fetch_query = "select * from app.add order by title";
            $fetch_run = mysqli_query($con, $fetch_query);

            if(mysqli_num_rows($fetch_run) > 0)
            {
                while($row = mysqli_fetch_array($fetch_run))
                {
                    $data .= '
                    <tr style="border: 1px solid black; padding: 8px; text-align: center">
                        <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
                        <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
                        <td>
                            <button onclick="DeleteUser('.$row['id'].')">Delete</button>
                        </td>
                    </tr>';
                }
            }
            $data .= '
                </table>
            </div>';
            
            header('Content-Type: text/html');
            exit($data);
        break;
        
        case 'dscd':
        
        break;
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement