douqin6785 2015-08-14 15:39
浏览 22

将数据插入数据库后,无需页面加载即可更新输出

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. 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

$(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

$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!";
    }
?>
  • 写回答

1条回答 默认 最新

  • dqc2017 2015-08-14 16:22
    关注

    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. ( 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:-

    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! Hope it helps, good luck

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP