简体   繁体   English

将数据插入数据库后获取输出以更新而无需页面加载

[英]Getting output to update without page load after inserting data into database

I am looking for a way that I can make this part of my code more interactive. 我正在寻找一种使我的代码的这一部分更具交互性的方法。 I send announcements through my form to ajax to my php file and it updates my db successfully. 我通过表单向Ajax发送公告到我的php文件,它成功更新了我的数据库。 My table outputs the data just fine. 我的表输出的数据很好。 How can I make the changes live though. 我如何才能使更改生效。 So if I add a new announcement, how can I get the table to update right away without a page reload? 因此,如果添加新公告,如何在不重新加载页面的情况下立即更新表?

Form to send Announcement 表格发送公告

$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );

try {
    //Prepare
     $con = mysqli_connect("localhost", "", "", "");
     if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {

        $user_stmt->execute();
        $user_stmt->bind_result($user_id); 

        if (!$user_stmt) {
            throw new Exception($con->error);
        }
     }
        $user_stmt->store_result();
         $user_result = array();
?>               
     <div class="announcement_success"></div>
            <p>Add New Announcement</p>
                <form action="" method="POST" id="insert_announcements">
                <input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
                    <textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
                    <label for="contactButton">
                        <button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
                    </label>
                </form>

Table

<?php
    if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.message, announcements.date, users.username FROM announcements
                            INNER JOIN users
                            ON announcements.user_id = users.id")) {


        $announcements_stmt->execute();
        $announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username); 

        if (!$announcements_stmt) {
            throw new Exception($con->error);
        }
        $announcements_stmt->store_result();
         $announcements_result = array();

?>

            Current Announcements
            <table>
                <tr>
                    <th>ID</th>
                    <th>Username</th>
                    <th>Message</th>
                    <th>Date</th>
                </tr>   
<?php
        while ($row = $announcements_stmt->fetch()) {
?>
                <tr>
                    <td><?php echo $announcements_id; ?></td>
                    <td><?php echo $announcements_username; ?></td>
                    <td><?php echo $announcements_messages; ?></td>
                    <td><?php echo $announcements_date; ?></td>
                </tr>   

<?php
        } 
?>

    }
            </table>
<?php           
    }
}

AJAX AJAX

$(document).ready(function(){ 
             $("#submit_announcement").on("click", function () {

             var user_message = $("#announcement_message").val();
                //$user = this.value;
                 $user = $("#approved_id").val();
                $.ajax({ 
                    url: "insert_announcements.php", 
                    type: "POST",
                    data: {
                           "user_id": $user,
                                        //"message": user_message
                                        "user_message": user_message
                            },
                    success: function (data) {
                           //  console.log(data); // data object will return the response when status code is 200
                             if (data == "Error!") {
                                 alert("Unable to get user info!");
                                 alert(data);
                             } else {
                                 $(".announcement_success").fadeIn();
                                 $(".announcement_success").show();
                                 $('.announcement_success').html('Announcement Successfully Added!');
                                 $('.announcement_success').delay(5000).fadeOut(400);
                             }
                         },
                         error: function (xhr, textStatus, errorThrown) {
                             alert(textStatus + "|" + errorThrown);
                             //console.log("error"); //otherwise error if status code is other than 200.
                         }
                     });
                 });
             });

PHP file that AJAX sends to AJAX发送到的PHP文件

$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true); 
file_put_contents('test.txt', $test); 
//var_dump($announcement_user_id);

$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
    if ( !$stmt2 || $con->error ) {
        // Check Errors for prepare
         die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
    }
    if(!$stmt2->bind_param('is', $announcement_user_id, $announcement_message)) {
        // Check errors for binding parameters
        die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
    }
    if(!$stmt2->execute()) {
        die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
    }
        //echo "Announcement was added successfully!";
    else
    {
         echo "Announcement Failed!";
    }
?>

As an example, you could probably do something like this. 例如,您可能可以执行以下操作。

/* insert into db script - more code above not shown */
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");

$errors=array();

if( !$stmt2 || $con->error ) $errors[]='Announcement INSERT prepare() failed: ' . htmlspecialchars( $con->error );
if( !$stmt2->bind_param( 'is', $announcement_user_id, $announcement_message ) ) $errors[]='Announcement INSERT bind_param() failed: ' . htmlspecialchars( $stmt2->error );
if( !$stmt2->execute() ) $errors[]='Announcement INSERT execute() failed: ' . htmlspecialchars( $stmt2->error );

echo json_encode( array(
    'user'          =>  $announcement_user_id,
    'announcement'  =>  $announcement_message,
    'status'        =>  empty( $errors ) ? 1 : 0, 
    'message'       =>  empty( $errors ) ? 'Announcement was added successfully!' : 'Announcement Failed!', 
    'errors'        =>  $errors ) );

The script will echo back a structured json object to the calling ajax function which can be processed by the assigned callback function. 该脚本会将结构化的json对象回显到调用的ajax函数,该函数可以由分配的回调函数进行处理。 ( success: function (data) {/**/} ) success: function (data) {/**/}

That callback function could be modified - something like:- 可以修改该回调函数-类似于:-

success: function( data ) {
    var json=typeof( data )=='string' ? JSON.parse( data ) : data;
    var msg=json.message;
    var user=json.user;
    var announcement=json.announcement;
    var status=parseInt( json.status );
    var errors=json.errors;

    if( Object.keys( errors ).length==0 && status==1 ){
        /*
        $(".announcement_success").fadeIn();
        $(".announcement_success").show();
        $('.announcement_success').html( msg );
        $('.announcement_success').delay(5000).fadeOut(400);    
        */
        /* Insert new row into table - assumed table has an id=updates !!!! */
        var tbl=document.getElementById('updates');
        var tbody=tbl.querySelectorAll('tbody')[0];
        var col=tbl.querySelectorAll('tr');
        var last=col[ col.length-1 ].id;

        var tr=createNode( 'tr',{}, null );
        createNode('td',{innerHTML:'? id ? '},tr);
        createNode('td',{innerHTML:user},tr);
        createNode('td',{innerHTML:announcement},tr);
        createNode('td',{innerHTML:'a date'},tr);
        insertAfter( tbody, tr, last );

    } else {
        var tmp=[];
        for( var e in errors ) tmp.push( errors[e] );
        alert( tmp.join( String.fromCharCode(10) ) );
    }
}

jQuery possibly has similar functions but the above relies upon these:- jQuery可能具有类似的功能,但以上功能依赖于这些功能:

function createNode( t, a, p ) {
    var el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
    for( var x in a ) if( a.hasOwnProperty( x ) && x!=='innerHTML' ) el.setAttribute( x, a[ x ] );
    if( a.hasOwnProperty('innerHTML') ) el.innerHTML=a.innerHTML;
    if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
    return el;
}
function insertAfter( p, n, r ) {
    p.insertBefore( n, r.nextSibling );
}   

I do not use jQuery so am unfamiliar with it's trickeries - but one thing to remember is to use console.log('some data here...') in your js code to aid debugging! 我不使用jQuery,所以不熟悉它的诡计-但是要记住的一件事是在您的js代码中使用console.log('some data here...')来帮助调试! Hope it helps, good luck 希望对您有帮助,祝您好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在数据库中插入数据后如何重新加载页面 - How to reload page after inserting data in database 将数据插入数据库后,加载引导模式作为警报 - load bootstrap modal as alert after inserting data to database 在不加载新页面的情况下将数据插入数据库PHP - Inserting data into database PHP without loading new page 将表单数据插入数据库后无法重定向到html页面 - Unable to redirect to html page after inserting form data into database AJAX重新加载页面而不插入数据库 - AJAX reloads the page without inserting into database 在 fetch() POST 请求已提交后使用 fetch() GET 请求以输出数据库数据而无需硬页面刷新 - Using A fetch() GET Request After A fetch() POST Request Has Been Submitted To Output Database Data Without A Hard Page Refresh 使用jquery mobile加载页面后更新数据主题 - Update data-theme after page load with jquery mobile 在 angularjs 中的控制器中获取数据后如何加载页面? - how to load page after getting data in controller in angularjs? 在数据库中插入数据并在没有刷新页面的情况下显示相同的数据(在插入数据库后调用数据) - insert data in database and show same data after insert without refresh page(call data after insert of database) 更新数据库而无需重新加载页面 - Update database without reloading page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM