带有2个提交按钮(保存和删除)的Wordpress Ajax表单提交如何使第二个按钮起作用

时间:2019-03-03 23:05:45

标签: javascript php ajax wordpress

我可以使用$ wpdb将记录保存在自定义表中。 javascript女巫处理了类型为Submit的一个输入,然后使用访存将数据操作和随机数发送到admin-ajax。我的插件具有添加操作功能,可以清除记录并将其保存在数据库表中。 我需要添加一个可以删除该记录的按钮,这是我遇到问题的地方。我试过一个单独的php文件,但找不到wpdb。因此,我正在尝试两个按钮调用不同的动作,但无法找到合适的wordpress ajax示例。我的代码如下 表格

<form id="changeCustAddr" action="#" method="post" data-url="<?php echo admin_url('/admin-ajax.php'); ?>">
<input type="hidden" name="action" value="cust_address">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'cust_address_nonce' )?>">
<input type="hidden" id="record" name="record" value="<?php echo (!$newone) ? $rec : $max+1 ?>">
<input type="hidden" id="custno" name="custno" value="<?php echo $custno ?>">

input fields for addresses
Prev, Next and New buttons etc have been removed for clarity

<input type="submit" id="CustAddrDelete" name="delete" class="btn" value="Delete" data-url="<?php echo bloginfo('template_directory') ?>/scripts/deleteCustAddrform.php?cust=<?php echo $custno ?>&record=<?php echo $rec ?>" >
<input type="button"  id="CustAddrNew" name="new" class="btn" value="New" data-url="<?php echo get_page_link( $post->ID ),'?cust=', $custno, '&record=new' ?>" >

<small class="field-msg js-form-submission">Submission in progress, Please wait &hellip;</small>
<small class="field-msg success js-form-success">Details Successfully submitted, thank you!</small>
<small class="field-msg error js-form-error">Could not update database. Please try again.</small>

<input type="submit" id="CustAddrSave" name="save" class="btn btn-blue" value="<?php echo (!$newone) ? 'Save' : 'Add New' ?>" data-action="cust_address">
<input type="button" id="CustAddrClose" name="close" class="btn btn-blue" value="<?php echo (!$newone) ? 'Close' : 'Discard Changes' ?>" data-url="<?php echo get_page_link( get_page_by_title( 'dojo details' )->ID ),'?cust=', $custno, '&record=1' ?>">

javascript

document.addEventListener('DOMContentLoaded', function (e) {
const changeCustAddrFrm = document.getElementById('changeCustAddr');
if (changeCustAddrFrm) {
    changeCustAddrFrm.addEventListener('submit', (e) => {
        e.preventDefault();

    let data = {
        custno: changeCustAddrFrm.querySelector('[name="custno"]').value,
        priority: changeCustAddrFrm.querySelector('[name="record"]').value,
        address1: changeCustAddrFrm.querySelector('[name="address1"]').value,
        ... more address lines ...
        postcode: changeCustAddrFrm.querySelector('[name="postcode"]').value,
  }
  // ajax http post request
  let url = changeCustAddrFrm.dataset.url;
  console.log(url);
  let params = new URLSearchParams(new FormData(changeCustAddrFrm));
  console.log(params);
  changeCustAddrFrm.querySelector('.js-form-submission').classList.add('show');

  fetch(url, {
      method: "POST",
      body: params
  }).then(res => res.json())
  .catch(error => {
      resetMessages();
      changeCustAddrFrm.querySelector('.js-form-error').classList.add('show');
  })
  .then(response => {
      resetMessages();

    if (response === 0 || response.status === 'error') {
                changeCustAddrFrm.querySelector('.js-form-error').classList.add('show');
                return;
            }

            changeCustAddrFrm.querySelector('.js-form-success').classList.add('show');
        })
});

和称为函数的ajax

public function cust_address() {
    if (!DOING_AJAX || !check_ajax_referer('cust_address_nonce', 'nonce')) {
        return $this->return_json('error');
    }
    $custno = $_POST['custno'];
    $addressno = $_POST['record'];
    $max = $_POST['max'];

    $servername = "localhost";
    $username = "uuuu";
    $password = "pppp";
    $dbname = "db";
    $mydb = new wpdb($username, $password, $dbname, $servername);
    $table = 'mem_custaddress';

    $data = [
        'Address1' => sanitize_text_field($_POST['address1']),
        // ... other address lines ...
        'Postcode' => sanitize_text_field($_POST['postcode']),
    ];
    $format = [ '%s', ... , '%s' ];
    $where = [
        'Custno' => $_POST['custno'],
        'Priority' => $_POST['record']
    ];
    $where_format = ['%d', '%d'];

    if ($addressno <= $max) {
        $result = $mydb->update($table, $data, $where, $format, $where_format);
    } else {
        $dataInsert = [
            'Custno' => $_POST['custno'],
            'Priority' => $_POST['record'],
            'Address1' => $_POST['Address1'],
            // ...
            'Postcode' => $_POST['Postcode'],
        ];
        $formatInsert = ['%d', '%d', '%s', ... , '%s'];
        $result = $mydb->insert($table, $dataInsert, $formatInsert);
    }

    if ($result) {
        return $this->return_json('success');
        wp_die();
    }
    return $this->return_json('error');
    wp_die();
}

public function return_json($status) {
    $return = [
        'status' => $status
    ];
    wp_send_json($return);
    wp_die();
}

如何使删除记录起作用?

1 个答案:

答案 0 :(得分:0)

经过大量搜索,我想出了一个解决方案。我希望有人可以帮助整理javascript。但是现在,表单数据将根据所按下的按钮来分离功能。

表格:

<form id="form1" data-url="<?php echo admin_url('/admin-ajax.php'); ?>">
    <input type="text" name="field1" class="m-2 border-2">
    <input type="text" name="field2" class="m-2 border-2">
    <input id="s1" type="submit" name="press" value="Press" class="btn">
    <input id="s2" type="submit" name="other" value="otherPress" class="btn">
</form>

javascript:

const form1 = document.getElementById('form1'),
s1 = document.getElementById('s1'),
s2 = document.getElementById('s2');
s1.addEventListener('click', (e) =>{
    e.preventDefault();
    let f1data = new FormData(form1);
    f1data.append('action', 'test');
    let params = new URLSearchParams(f1data);
    let url = form1.dataset.url;
    fetch(url, {
        method: 'post',
        body:  params
    }).then(function (response){
        return response.text();
    }).then(function (text){
        console.log('me', text);
    }).catch(function (error){
        console.error(error);
    })
})
s2.addEventListener('click', (e) =>{
    e.preventDefault();
    let f1data = new FormData(form1);
    f1data.append('action', 'other');
    let params = new URLSearchParams(f1data);
    let url = form1.dataset.url;
    fetch(url, {
        method: 'post',
        body:  params
    }).then(function (response){
        return response.text();
    }).then(function (text){
        console.log('me', text);
    }).catch(function (error){
        console.error(error);
    })
})

和称为函数的ajax:

add_action( 'wp_ajax_test', array($this, 'test') );
add_action( 'wp_ajax_other', array($this, 'other') );

public function test() {
    var_dump($_POST);
}

public function other() {
    var_dump($_POST);
}