Отправка формы Wordpress Ajax с 2 кнопками отправки (сохранить и удалить), как заставить работать 2-ю кнопку

0

Я могу сохранить записи в моей пользовательской таблице, используя $ wpdb. Один ввод типа submit обрабатывается в javascript witch, а затем использует fetch для отправки действия с данными и nonce в 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();
}

Как я могу получить удаление записи для работы?

  • 0
    Вам просто нужно отправить что-то обратно на серверный mode и иметь один mode:'save' нажатия кнопки mode:'save' а другой mode:'delete' вы можете включить это в бэкэнде.
  • 1
    Спасибо @Dharman за ваше редактирование в php. Мне придется изменить array () на [] и во многих других файлах. Я также посмотрю на линнинг php и следую правильным стандартам.
Показать ещё 1 комментарий

1 ответ

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>

Яваскрипт:

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);
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню