通过AJAX请求获取和删除数据

时间:2019-11-08 作者:Ataur Rahman

我使用ajax创建了一个crud预订表单。此表单的目的是当用户提交此表单时,用户数据将存储在数据库中,而无需刷新页面。完整功能将被crud,无需页面刷新。已成功插入、编辑、更新和删除数据。整个机制工作正常,但问题是

编辑用户数据然后更新时。数据已更新,但在此字段和表格中显示以前的数据。刷新显示更新数据的页面后

删除用户数据时,数据将从数据库中删除,但在此表中显示以前的数据。

/*
Plugin Name: Crud Frontend
Plugin URI: http://example.com
Description: Crud Frontend
Version: 1.0
Author: Ataur Rahman
Author URI: md-ataur.github.io
License: GPL v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: crud-frontend
*/

defined( \'ABSPATH\' ) or die( \'No script kiddies please!\' );

if(!class_exists(\'CrudAjaxReservationForm\')){

    class CrudAjaxReservationForm{

        public function __construct(){
            add_action(\'plugins_loaded\', array($this, \'crudfrontend_load_textdomain\' ));            
            add_action(\'wp_enqueue_scripts\', array($this, \'crudfrontend_enqueue_scripts\'));
            add_shortcode( \'crud_ajax_form\', array($this,\'crudfrontend_shortcode\' ));
            add_action( \'wp_ajax_ajaxRSF\', array($this, \'AjaxdataProcess\') );
            add_action( \'wp_ajax_nopriv_ajaxRSF\', array($this, \'AjaxdataProcess\') );
            register_activation_hook( __FILE__, array($this,\'crud_table_init\') );
        }

        function crud_table_init(){
            global $wpdb;
            $table_name = $wpdb->prefix."crudfrontend";

            /* Table create in Database */
            $sql = "CREATE TABLE {$table_name} (
                id INT NOT NULL AUTO_INCREMENT,
                name VARCHAR(250),
                email VARCHAR(250),
                phone VARCHAR(250),
                person INT(11),
                date DATE,
                time TIME,
                message VARCHAR(250),
                PRIMARY KEY (id)
            );";
            require_once(ABSPATH."wp-admin/includes/upgrade.php");
            dbDelta( $sql );        
        }

    public function crudfrontend_load_textdomain(){
        load_plugin_textdomain( \'crud-frontend\', false, dirname( plugin_basename( __FILE__ ) ) . \'/languages\' );
    }
    public function crudfrontend_enqueue_scripts(){
        wp_enqueue_style( \'bootstrap\', plugin_dir_url( __FILE__ ).\'assets/public/css/bootstrap.min.css\');
        wp_enqueue_script( \'crud-ajax-reservation-js\', plugin_dir_url( __FILE__ ).\'assets/public/js/crud-ajax-reservation.js\', array( \'jquery\' ), time(), true );
        $ajaxUrl = admin_url( \'admin-ajax.php\');
        wp_localize_script( \'crud-ajax-reservation-js\', \'url\', array(\'ajaxUrl\' => $ajaxUrl) );
    }

    public static function AjaxdataProcess(){
        global $wpdb;
        $table_name = $wpdb->prefix."crudfrontend";
        if (check_ajax_referer( \'rsf_nonce_action\', \'rn\', false )) {
            $uid    = sanitize_key( isset($_POST[\'uid\'])?$_POST[\'uid\']:\'\' );
            $name   = sanitize_text_field( isset($_POST[\'RFname\'])?$_POST[\'RFname\']:\'\' );
            $email  = sanitize_email( isset($_POST[\'RFemail\'])?$_POST[\'RFemail\']:\'\' );
            $phone  = sanitize_text_field( isset($_POST[\'RFphone\'])?$_POST[\'RFphone\']:\'\' );
            $person = sanitize_text_field( isset($_POST[\'RFperson\'])?$_POST[\'RFperson\']:\'\' );
            $date   = sanitize_text_field( isset($_POST[\'RFdate\'])?$_POST[\'RFdate\']:\'\' );
            $time   = sanitize_text_field( isset($_POST[\'RFtime\'])?$_POST[\'RFtime\']:\'\' );
            $message = sanitize_text_field( isset($_POST[\'RFMessage\'])?$_POST[\'RFMessage\']:\'\' );        
            if (!empty($name) && !empty($email) && !empty($phone) && !empty($person) && !empty($date) && !empty($time)) {
                $data = array(                  
                    \'name\' =>  $name,
                    \'email\' =>  $email,
                    \'phone\' =>  $phone,
                    \'person\' =>  $person,
                    \'date\' =>  $date,
                    \'time\' =>  $time,
                    \'message\' =>  $message,
                );
                //print_r($data);
                if ($uid) {
                    $wpdb->update("{$table_name}", $data, [\'id\'=>$uid]);                    
                    die (\'<p class="alert alert-success">Successfully Data Updated</p>\');
                }else{
                    $wpdb->insert("{$table_name}", $data);
                    die (\'<p class="alert alert-success">Successfully Data Stored</p>\');
                }               
            }else{
                die(\'<p class="alert alert-danger">Fields must no be empty</p>\');
            }
        }
    }
    public static function crud_ajax_form(){
        global $wpdb;
        $table_name = $wpdb->prefix."crudfrontend";
        $id = sanitize_key(isset($_GET[\'uid\']) ? $_GET[\'uid\']: null);
        if ($id) {
            $result = $wpdb->get_row("SELECT * FROM {$table_name} WHERE id=\'{$id}\'");
        }/* Data retrieve mechanism */      

        if (isset($_GET[\'action\']) && $_GET[\'action\'] == "delete") {
            $wpdb->delete($table_name, [\'id\'=>sanitize_key($_GET[\'uid\'])]);
            $id = null;
        }/* Delete Mechanism */

        ?>
        <div class="container">         
            <div class="col-md-6 offset-md-3">
                <div id="message"></div>
                <form action="<?php the_permalink(); ?>" id="Rform">
                    <?php wp_nonce_field( \'rsf_nonce_action\', \'rsf_nonce_field\');?>                 
                    <div class="form-group">
                        <label for="name" class="label"><?php _e(\'Name\',\'crudfrontend\');?></label>
                        <input type="text" class="form-control" id="RFname" value="<?php if($id) echo esc_attr($result->name);?>">
                    </div>
                    <div class="form-group">
                        <label for="email" class="label"><?php _e(\'Email\',\'crudfrontend\');?></label>
                        <input type="email" class="form-control" id="RFemail"value="<?php if($id) echo esc_attr($result->email);?>">                           
                    </div>
                    <div class="form-group">
                        <label for="phone" class="label"><?php _e(\'Phone\',\'crudfrontend\');?></label>
                        <input type="text" class="form-control" id="RFphone"value="<?php if($id) echo esc_attr($result->phone);?>">
                    </div>
                    <div class="form-group">
                        <label for="persons" class="label"><?php _e(\'Number of Persons\',\'crudfrontend\');?></label>
                        <select name="persons" id="RFperson" class="form-control">
                            <option value="1" <?php if( $id && $result->person=="1") echo \'selected="selected"\'; ?> ><?php _e(\'1 person\',\'crudfrontend\');?></option>
                            <option value="2" <?php if( $id && $result->person=="2") echo \'selected="selected"\'; ?>><?php _e(\'2 person\',\'crudfrontend\');?></option>
                            <option value="3" <?php if( $id && $result->person=="3") echo \'selected="selected"\'; ?>><?php _e(\'3 person\',\'crudfrontend\');?></option>
                            <option value="4" <?php if( $id && $result->person=="4") echo \'selected="selected"\'; ?>><?php _e(\'4 person\',\'crudfrontend\');?></option>
                            <option value="5" <?php if( $id && $result->person=="5") echo \'selected="selected"\'; ?>><?php _e(\'5 person\',\'crudfrontend\');?></option>
                        </select>                            
                    </div>
                    <div class="row">
                        <div class="form-group col-md-6">
                            <label for="date" class="label"><?php _e(\'Date\',\'crudfrontend\');?></label>
                            <input type="date" class="form-control" id="RFdate"value="<?php if($id) echo esc_attr($result->date);?>">                               
                        </div>
                        <div class="form-group col-md-6">
                            <label for="time" class="label"><?php _e(\'Time\',\'crudfrontend\');?></label>
                            <input type="time" class="form-control" id="RFtime" value="<?php if($id) echo esc_attr($result->time);?>"autocomplete="off">
                        </div>
                    </div>   
                    <div class="form-group">
                        <textarea class="form-control" id="RFMessage" rows="5"><?php if($id) echo esc_attr($result->message);?></textarea>
                    </div>                                          
                    <div class="row justify-content-center">                        
                        <?php 
                        if ($id) {
                            echo \'<input type="hidden" name="id" id="uid" value="\'.$result->id.\'">\';
                            ?>
                            <button id="reserveForm" class="btn btn-primary"><?php _e(\'Update\',\'crudfrontend\');?></button>&nbsp;
                            <a class="btn btn-primary" href="<?php the_permalink();?>"><?php _e(\'Back\',\'crudfrontend\');?></a>
                            <?php
                        }else{
                            ?>
                            <button id="reserveForm" class="btn btn-primary"><?php _e(\'Reserve Now\',\'crudfrontend\');?></button>
                            <?php
                        }
                        ?>                      
                    </div>
                </form>
            </div>
            <div class="col-md-12">
                <h5><?php _e("Data Show","crudfrontend");?></h5>                        
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th scope="col"><?php _e("ID","crudfrontend");?></th>
                            <th scope="col"><?php _e("Name","crudfrontend");?></th>
                            <th scope="col"><?php _e("Email","crudfrontend");?></th>
                            <th scope="col"><?php _e("Phone","crudfrontend");?></th>
                            <th scope="col"><?php _e("Date","crudfrontend");?></th>
                            <th scope="col"><?php _e("Time","crudfrontend");?></th>
                            <th scope="col"><?php _e("Message","crudfrontend");?></th>
                            <th scope="col"><?php _e("Action","crudfrontend");?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        global $wpdb;
                        $table_name = $wpdb->prefix."crudfrontend";
                        $users = $wpdb->get_results("SELECT * FROM {$table_name} ORDER BY id DESC", ARRAY_A);
                        foreach ($users as $user) {
                            ?>
                            <tr>
                                <th scope="row"><?php echo esc_html( $user[\'id\'] ); ?></th>
                                <td><?php echo esc_html( $user[\'name\'] ); ?></td>
                                <td><?php echo esc_html( $user[\'email\'] ); ?></td>
                                <td><?php echo esc_html( $user[\'person\'] ); ?></td>
                                <td><?php echo esc_html( $user[\'date\'] ); ?></td>
                                <td><?php echo esc_html( $user[\'time\'] ); ?></td>
                                <td><?php echo esc_html( $user[\'message\'] ); ?></td>
                                <td><span><a href="?uid=<?php echo esc_html( $user[\'id\'] ); ?>">Edit</a></span>&nbsp;&nbsp;<span><a href="?uid=<?php echo esc_html( $user[\'id\'] ); ?>&action=delete">Delete</a></span></td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>          
        </div>
        <?php
    }

    public function crudfrontend_shortcode(){
            // Turn on output buffering.
            ob_start();

            self::crud_ajax_form(); // echo the form

            // Turn off output buffering and then return the output echoed via the above functions.
            return ob_get_clean();
        }
    }

    new CrudAjaxReservationForm;
}
Javascript

;(function($){
        $(document).ready(function(){       
            $(\'#reserveForm\').on(\'click\', function(){
                $.post(url.ajaxUrl, {
                    action: \'ajaxRSF\',
                    rn: $(\'#rsf_nonce_field\').val(),
                    RFname: $(\'#RFname\').val(),
                    uid: $(\'#uid\').val(),
                    RFemail: $(\'#RFemail\').val(),
                    RFphone: $(\'#RFphone\').val(),
                    RFperson: $(\'#RFperson\').val(),
                    RFdate: $(\'#RFdate\').val(),
                    RFtime: $(\'#RFtime\').val(),
                    RFMessage: $(\'#RFMessage\').val()                
                }, function(data) {
                    $(\'#message\').html(data);
                    console.log(data);
                    $(\'#Rform\')[0].reset();
                });         
                return false;
            });
        });
    })(jQuery);

enter image description here

1 个回复
SO网友:Shadow

当你编辑或删除任何记录时,为什么不再次替换HTML呢!

这里可以做什么:编辑/删除查询完成后,必须编写查询,以便再次从SQL中提取数据,并使用ajax响应进行替换。

相关推荐

Php.ini中的UPLOAD_max_FILESIZE错误

我在上载大约2.3 MB大小的下载主题时出错,上载的文件超过了php中的upload\\u max\\u filesize指令。ini。当我尝试将upload\\u max\\u filesize=10MB的值从默认的2M更改为所有php时。ini,php。ini开发和php。ini生产我也遇到了同样的错误。我无法上载我下载的主题,而其大小约为2.3 MB。我正在使用XAMPP。提前谢谢。