简体   繁体   中英

Getting php results to show after AJAX call without page reload

I have three sections on a page. Pending, Accepted, and Denied users. I output all of this data through a php while loop. Next to the Pending users section, for each user in that section I have two buttons (Accept and Deny). When either of those buttons are pressed I run an Ajax call to my php file that updates the users status to either Accepted or Denied (whichever was pressed).

The issue I am having is without letting the page refresh the user's data will not moved to the updated status section(Everything updates correctly on the db side). However, if I move out the return false; code the page refreshes, but my $('#success').html('User Status Changed!'); $('#success').delay(5000).fadeOut(400); $('#success').html('User Status Changed!'); $('#success').delay(5000).fadeOut(400); goes away right when the page refreshes, so almost instantly.

I need a way that the page does not refresh, but my user's data is moved to the appropriate section, so my success message still appears.

$(document).ready(function () {

$('.approve').click(function () {
    $.ajax({
        url: 'userRequest_approve.php',
        type: 'POST',
        data: {
            id: $(this).val(), //id
            status: 'Approved' //status
        },
        success: function (data) {
            //do something with the data that got returned
            $("#success").fadeIn();
            $("#success").show();
            $('#success').html('User Status Changed!');
            $('#success').delay(5000).fadeOut(400);
        },
        //type: 'POST'
    });
    return false;
});
});

Form

<form action="" method="POST" id="status">


  <input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id' />
    <?php if ($pending_firstname==t rue) { echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" . "Username - ". $pending_username . "</br></br>" //echo print_r($_POST); ?>
</form>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">Deny</button>
<br>
<br>
<br>
<?php ;} else { echo "There are no Pending Requests at this time."; }

Code for the html part:

<?php
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);

    if( $numrows ) {
        while($row = mysqli_fetch_assoc($run)){
            if($row['status'] == "Pending"){

                $pending_id        = $row['id'];
                $pending_user_id   = $row['user_id'];
                $pending_firstname = $row['firstname'];
                $pending_lastname  = $row['lastname'];
                $pending_username  = $row['username'];
?>
        <form action="" method="POST" id="status">
             <input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
        if ($pending_firstname == true) {
            echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" . 
                "Username - ". $pending_username . "</br></br>"
                //echo print_r($_POST);
?>


                        <button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
                        <button id="deny" type="submit" form="status" name="deny" value="Denied">Deny</button>
                        </form><br><br><br>
<?php   
                    ;} else {
                        echo "There are no Pending Requests at this time.";
                    }
                }
            }
        }
?>
<hr><br>

        <h2>Approved User Requests</h2><br>
        <div id="success" style="color: red;"></div><br>
    <?php
        $con2 = mysqli_connect("localhost", "root", "", "db");
        $run2 = mysqli_query($con2,"SELECT * FROM user_requests ORDER BY id DESC");
        $numrows2 = mysqli_num_rows($run2);

            if( $numrows2 ) {
                while($row2 = mysqli_fetch_assoc($run2)){
                    if($row2['status'] == "Approved"){

                        $approved_id        = $row2['user_id'];
                        $approved_firstname = $row2['firstname'];
                        $approved_lastname  = $row2['lastname'];
                        $approved_username  = $row2['username'];

        if ($approved_firstname == true) {
            echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" . 
                "Username - ". $approved_username . "</br></br>"
?>

Try this. You are trapping the click event, which doesn't stop the form submission. If you change your handler to on submit and prevent the default action then this should work.

$(document).ready(function () {

$('#status').on('submit', function (event) {
event.preventDefault();

    $.ajax({
        url: 'userRequest_approve.php',
        type: 'POST',
        data: {
            id: $(this).val(), //id
            status: 'Approved' //status
        },
        success: function (data) {
            //do something with the data that got returned
            $("#success").fadeIn();
            $("#success").show();
            $('#success').html('User Status Changed!');
            $('#success').delay(5000).fadeOut(400);
        }
        //type: 'POST'
    });

});
});

Form

<form action="" method="POST" id="status">


  <input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id' />
    <?php if ($pending_firstname == true) { echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" . "Username - ". $pending_username . "</br></br>" //echo print_r($_POST); ?>

<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">Deny</button>


</form>
<br>
<br>
<br>
<?php ;} else { echo "There are no Pending Requests at this time."; }

NEW EDIT Section TRY THIS

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>
<body>

<?php
    $con = mysqli_connect("localhost", "root", "", "db");
    $run = mysqli_query($con,"SELECT * FROM user_requests WHERE status='Pending' ORDER BY id DESC");
    $numrows = mysqli_num_rows($run);

    if( $numrows ) {
        while($row = mysqli_fetch_assoc($run)){
            if($row['status'] == "Pending"){

                $pending_id        = $row['id'];
                $pending_user_id   = $row['user_id'];
                $pending_firstname = $row['firstname'];
                $pending_lastname  = $row['lastname'];
                $pending_username  = $row['username'];

                if ($pending_firstname == true) {

                    // note removed ID
                    echo '<form action="" method="POST">';
                    echo "Name - " . $pending_firstname . " " . $pending_lastname . "</br>" . "Username - " . $pending_username . "</br></br>";
                    echo '<button class="approve" type="submit"  name="approve" action="Approved"  value="', $pending_id ,'">Approve</button>';
                    echo '<button class="deny" type="submit"  name="deny"  action="Denied"  value="', $pending_id ,'" >Deny</button>';
                    echo '</form><br><br><br>';

                }
            }
        }
    }
    else {
        echo "There are no Pending Requests at this time.";
    }
?>
<hr><br>

<h2>Approved User Requests</h2><br>
<div id="success" style="color: red;"></div><br>
<?php
    $con2 = mysqli_connect("localhost", "root", "", "db");
    $run2 = mysqli_query($con2,"SELECT * FROM user_requests WHERE status='Approved' ORDER BY id DESC");
    $numrows2 = mysqli_num_rows($run2);

    if( $numrows2 ) {

        while($row2 = mysqli_fetch_assoc($run2))
        {
            $approved_id        = $row2['user_id'];
            $approved_firstname = $row2['firstname'];
            $approved_lastname  = $row2['lastname'];
            $approved_username  = $row2['username'];

            if ($approved_firstname == true)
            {
                echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
                    "Username - ". $approved_username . "</br></br>";
            }
        }
    }
    else
    {
        // none already in approved status

    }
?>

<script type="text/javascript">

    $(document).ready(function(){

        // button handler
        $('button').on('click', function (event) {
            event.preventDefault();

            // get the button that was pressed
            var _button =  $(this);
            // get the value of this button
            var _val = _button.val();

            // get the action for the button (Either Approved or Denied)
            var _action = _button.attr('action');

            // get the form the button is in
            var _form = _button.closest('form');

            var _dataPassed = {status:_action,id:_val};

            // log the data I'm seding  (for debug)
            console.log(_dataPassed);

            // Trigger a submit event and pass the submit handler the value of the button pressed.    
            _form.triggerHandler('submit', _dataPassed);

        });


        $('form').submit(function (event, Passeddata) {
            // prevent the submit event so the page doesn't refresh.
            event.preventDefault();

            // make a ajax request with the value of the button that was pressed.
            $.ajax({
                url: 'userRequest_approve.php',
                type: 'POST',
                data: Passeddata,
                success: function (data) {
                    //do something with the data that got returned
                    $("#success").fadeIn();
                    $("#success").show();
                    $('#success').html('User Status Changed!');
                    $('#success').delay(5000).fadeOut(400);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // alert on an http error
                    alert(textStatus + errorThrown);
                }
            });

        });

    });
</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM