JQuery AJAX отправка со значениями формы - PullRequest
0 голосов
/ 27 августа 2018

Я написал некоторый код jQuery, который отправляет запрос AJAX в мою CMS для запуска различных действий PHP в зависимости от того, какое действие отправлено в запросе.

Это работает нормально, однако значения формы не отправляются с постом AJAX. Я пробовал различные методы, такие как новая форма и сериализация данных формы, но мне кажется, что ничего не работает.

Я предполагал, что простого включения этого в вызов будет достаточно:

$formData = $('#checkout-cart').serialize();
data: $formData,  

Может кто-нибудь указать мне правильное направление, пожалуйста?

var formSubmit = {
    config: {
        guestUser: '.create-guest-user',
    },
    initialize: function () {
        var $this = this;
        $(this.config.guestUser).click(function(event) {
            event.preventDefault();
            $this.createGuestUser();
            return false;
        });
    },
    // Create Guest User
    createGuestUser: function (elem) {
        $.post(window.location.href, {
            type: 'ajax',
            data: $formData,
            url: window.location.href,
            action: 'createGuestUser',
        }).done(function (response) {
            $('.create-guest-user').addClass('disabled');
        });
    }
};

$(document).ready(function () {
    formSubmit.initialize();
});

HTML

<form id="checkout-form" action="cart/checkout/" method="post">
  <div class="row">
    <div class="col-sm-6">
      <fieldset id="account">
        <legend>Your Personal Details</legend>
        <div class="form-group" style="display: none;">
          <label class="control-label">Customer Group</label>
          <div class="radio">
            <label>
              <input type="radio" name="customer_group_id" value="1" checked="checked">
              Default
            </label>
          </div>
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-firstname">First Name</label>
          <input type="text" name="firstname" value="" placeholder="First Name" id="input-payment-firstname" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-lastname">Last Name</label>
          <input type="text" name="lastname" value="" placeholder="Last Name" id="input-payment-lastname" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-email">E-Mail</label>
          <input type="text" name="email" value="" placeholder="E-Mail" id="input-payment-email" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-telephone">Telephone</label>
          <input type="text" name="telephone" value="" placeholder="Telephone" id="input-payment-telephone" class="form-control">
        </div>
      </fieldset>
    </div>
    <div class="col-sm-6">
      <fieldset id="address" class="required">
        <legend>Your Address</legend>
        <div class="form-group">
          <label class="control-label" for="input-payment-company">Company</label>
          <input type="text" name="company" value="" placeholder="Company" id="input-payment-company" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-address-1">Address 1</label>
          <input type="text" name="address_1" value="" placeholder="Address 1" id="input-payment-address-1" class="form-control">
        </div>
        <div class="form-group">
          <label class="control-label" for="input-payment-address-2">Address 2</label>
          <input type="text" name="address_2" value="" placeholder="Address 2" id="input-payment-address-2" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-city">City</label>
          <input type="text" name="city" value="" placeholder="City" id="input-payment-city" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-postcode">Post Code</label>
          <input type="text" name="postcode" value="" placeholder="Post Code" id="input-payment-postcode" class="form-control">
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-country">Country</label>
          <select name="country_id" value="" id="input-payment-country" class="form-control">
            <option value="244">Aaland Islands</option><option value="1">Afghanistan</option>
          </select>
        </div>
        <div class="form-group required">
          <label class="control-label" for="input-payment-zone">Region / State</label>
          <select name="zone_id" value="" id="input-payment-zone" class="form-control">
          </select>
        </div>
      </fieldset>
    </div>
  </div>

  <div class="buttons">
    <div class="pull-right">
      <button id="button-guest" class="btn btn-primary create-guest-user get-shipping-methods" data-loading-text="Loading...">Continue</button>
    </div>
  </div>

</form>

Ответы [ 2 ]

0 голосов
/ 28 августа 2018

Второй аргумент $.post - это просто данные поста, а не аргумент опций. Если вы хотите передать опции, вам нужно использовать $.ajax, а не $.post.

Вам также необходимо обновить $formData при выполнении вызова AJAX, в противном случае вы получите значения формы с момента первоначальной загрузки страницы.

Нет опции action для $.ajax. Если вы хотите добавить дополнительные параметры POST, которых нет в формах ввода, вам нужно добавить их в $formData.

createGuestUser: function (elem) {
    var $formData = 'action=createGuestUser&' + $('#checkout-cart').serialize();
    $.ajax({
        type: 'post',
        data: $formData,
        url: window.location.href,
    }).done(function (response) {
        $('.create-guest-user').addClass('disabled');
    });
}
0 голосов
/ 27 августа 2018

Пожалуйста, добавьте атрибут url к вашему $.post

  var formSubmit = {
      config: {
          guestUser: '.create-guest-user',
      },
      initialize: function () {
          var $this = this;
          $(this.config.guestUser).click(function(event) {
              event.preventDefault();
              $this.createGuestUser();
              return false;
          });
      },
      // Create Guest User
      createGuestUser: function (elem) {
          $.ajax({
              type: 'post',
              data: $formData,
              url: 'url.php'
          }).done(function (response) {
              $('.create-guest-user').addClass('disabled');
          });
      }
  };

  $(document).ready(function () {
      formSubmit.initialize();
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...