【问题标题】:WordPress save data to DB via AJAXWordPress 通过 AJAX 将数据保存到数据库
【发布时间】:2021-03-08 15:36:24
【问题描述】:

一般来说,我对 WordpPress 和 Web 开发还是很陌生。 尝试通过 ajax 调用将数据从页面上的表单保存到 wordpress 数据库。

这是我的表格:

             <form type="post" action="" id="MSRPForm">
                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputEmail" class="col-sm-4 col-form-label" >Email</label>
                        <div class="col-sm-8">
                            <input name="Email" type="text" class="form-control-plaintext" id="inputEmail"
                            placeholder="email@example.com">
                        </div>
                    </div>
                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputZipCode" class="col-sm-4 col-form-label" >Zip Code</label>
                        <div class="col-sm-8">
                            <input name="ZipCode" type="text" class="form-control" id="inputZipCode" placeholder="Enter your Zip Code">
                        </div>
                    </div>

                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputMSRP" class="col-sm-6 col-form-label font-weight-bold" >MSRP<br><small>Manufacturer's Suggested Retail Price</small></label>
                        
                        <div class="col-sm-6">
                        <input name="MSRP" type="text" min="1000" class="form-control text-right" id="inputMSRP" placeholder="Enter the MSRP">
                        </div>
                    </div>
                    <button id="msrp-btn" type="button" class="btn btn-primary my-2">Calculate</button>
                </form>

这是一个 AJAX。它被包装在 jQuery 函数中,所以它肯定可以工作:

 let ajaxurl = "wp-admin/admin-ajax.php";
$(document).ready(function(){
    $("#msrp-btn").click(function(e) {
        e.preventDefault();       
        let email = $('#inputEmail').val();
        let zipCode = $('#inputZipCode').val();
        let msrp = $('#inputMSRP').val();

        let info = {
            'action': 'addMSRP',
            'email': email,
            'zipCode' : zipCode,
            'msrp' : msrp
        };
            
        
        jQuery.ajax({
            type: "POST",
            url: ajaxurl, 
            data: info,
            beforeSend: function() {            
                $('#myModal').modal('show'); 
                // console.log( info);
            },
            success: function(res){
                console.log(res);
            },
            error: function(res){
                console.log(res)
            },
        }); 

    });  
});

最后这是我的functions.php中的代码

    add_action('wp_ajax_addMSRP', 'addMSRP');
add_action('wp_ajax_nopriv_addMSRP', 'addMSRP');

function addMSRP() {

    global $wpdb;

    $email = $_POST['Email'];
    $zipCode = $_POST['ZipCode'];
    $MSRP = $_POST['MSRP'];
    
    
    if ( $wpdb->insert( 'msrp_info', array(
        'email' => $email,
        'zipCode' => $zipCode,
        'MSRP' => $MSRP
    ) ) === false ) {
        wp_die('Database Insertion failed'); 
    } else {
        echo "Info successfully added, row ID is ".$wpdb->insert_id;
    }
    exit();
}

看起来代码正在工作,因为数据被传递到服务器,但它没有被保存到数据库。 如果有人能告诉我我做错了什么,我将不胜感激。谢谢。

【问题讨论】:

  • 您遇到的错误是什么?您是否在 wp_config.php 中打开了 WP DEBUG?另外请尝试在此行之后添加wp_die();echo "Info successfully added, row ID is ".$wpdb-&gt;insert_id;
  • @ozgur 我在控制台中收到“数据库插入失败”。不,我没有。会这样做。谢谢。
  • 如果您已经收到错误消息,则无需启用 WP DEBUG。
  • 您可以尝试在wp_die('Database Insertion failed');行之前添加echo $wpdb-&gt;show_errors();以显示DB错误。
  • 我注意到您没有使用相同的大小写字母。我不确定,但这可能是您问题的根源。也许您的数据库不接受空值。例如,您从 ajax 发送所有小写的 msrp,但您尝试使用全部大写的 $MSRP = $_POST['MSRP']; 读取它。

标签: php ajax wordpress ajaxform wordpress-database


【解决方案1】:

我可以看到一些问题,即您没有将正确的变量传递给 $_POST。您还需要指定数据库表的名称。试试下面的代码插入数据库。

add_action('wp_ajax_addMSRP', 'addMSRP');
add_action('wp_ajax_nopriv_addMSRP', 'addMSRP');  

function addMSRP(){
    
        global $wpdb;
        //output will be your debug tool - if it posts it works.
        $output = ['status' => 1];
        $email = sanitize_text_field($_POST["email"]);
        $zipcode = sanitize_text_field($_POST["zipCode"]);
        $MSRP = sanitize_text_field($_POST["msrp"]);
    
        $table = $wpdb->prefix . 'enteryourdatabasename';
        //This below code has to match exactly what the database reads.
        //If 'msrp' in the database the table is 'MsRp' - than replace it as spelled below. 
        $data = array(
            'email' => $email,
            'zipcode' => $zipcode,
            'msrp' => $MSRP,
            
        );
    
        $wpdb->insert($table, $data);
    //using wp_send_json to send that response and kill script.
        $output['status'] = 2;
        wp_send_json($output);
    
    
    
    }

【讨论】:

  • 谢谢!看来我首先需要在 DB 中创建一个表。
猜你喜欢
  • 1970-01-01
  • 2014-02-17
  • 2018-02-02
  • 1970-01-01
  • 2017-09-01
  • 2017-09-17
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
相关资源
最近更新 更多