Передача определенных значений формы с помощью POST - PullRequest
0 голосов
/ 30 марта 2019

Что я пытаюсь сделать, так это то, что после отправки формы она передает определенные значения из формы в PayPal.

Это мой код формы:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form class="form-horizontal" action="<?php echo whichPPUrl(); ?>" method="post" id="paypal_form" target="_blank">

  <div class="form-group">
    <label class="control-label col-xs-4" for="text">URL:</label> 
    <div class="col-xs-8">
      <input id="text" name="url" placeholder="site.com" type="text" class="form-control" required="required">
    </div>
  </div>
  <div class="form-group">

    <label class="control-label col-xs-4" for="checkbox">&nbsp;</label> 
    <div class="col-xs-8">
      <div class="checkbox">
        <label class="checkbox">
          <input type="checkbox" class="sum" name="metrics_1" value="1.00">
              <strong>Moz</strong> - DA/PA/MozRank/Links In/Equity
        </label>
      </div>

      <div class="checkbox">
        <label class="checkbox">
          <input type="checkbox" class="sum" name="metrics_2" value="1.00">
              <strong>SEMRush</strong> - Rank/Keywords Number/Traffic/Costs/URL Links Number/Hostname Links Number/Domain Links Number
        </label>
      </div>

      <div class="checkbox">
        <label class="checkbox">
          <input type="checkbox" class="sum" name="metrics_3" value="1.00">
              <strong>Majestic</strong> - Rank/Keywords Number/Traffic/Costs/URL Links Number/Hostname Links Number/Domain Links Number
        </label>
      </div>

      <div class="checkbox">
        <label class="checkbox">
          <input type="checkbox" class="sum" name="metrics_4" value="1.00">
              <strong>Backlinks</strong> - Get any backlinks found for your domain plus anchor text (250 max.)
        </label>
      </div>
    </div>

  </div>

  <div class="form-group">
    <label for="total" class="control-label col-xs-4">Cost ($):</label> 
    <div class="col-xs-8">
      <input id="total" name="cost" type="text" class="form-control">
      </div>
    </div>
  </div>

  <div class="form-group">
    <label for="total" class="control-label col-xs-4">&nbsp;</label> 
    <div class="col-xs-8">
      <input type="hidden" name="cmd" value="_xclick" />
      <input type="hidden" name="business" value="contact@site.co.uk">
      <input type="hidden" name="item_name" value="Wraith Metrics">
      <input type="hidden" name="item_number" value="1">
      <input type="hidden" name="currency_code" value="USD">
      <input type="hidden" name="custom" value="getTheFormValues()">
      <input type="hidden" name="amount" value="getAndPassTheCost()">
      <input type="hidden" name="return" value="https://www.wraithseo.com/custom-metrics-builder.php?paid=1">
      <input type="hidden" name="notify_url" value="https://www.wraithseo.com/gateway/ipn.php">
      <input type="image" src="images/purchase.png" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
      </div>
    </div>
  </div>

</form>

<script>
    // pass the total value over to the form: <input type="hidden" name="amount" value="getTheCost()">
    function getAndPassTheCost() {
        return $("#total").val();
    }
</script>   

<script>
    // pass the form values over and deal with them on the backend: <input type="hidden" name="custom" value="getTheFormValues()">
    function getTheFormValues() {
        return $("form").serialize();
    }
</script>   

<script>    
$(document).ready(function() {
    // updates / adds the checkbox values
    function updateSum() {
      var total = "0.00";
      $(".sum:checked").each(function(i, n) {
         let sum = parseFloat(total) + parseFloat($(n).val());
         total = sum.toFixed(2);
      });
      $("#total").val(total);
    }
    // run the update on every checkbox change and on startup
    $("input.sum").change(updateSum);
    updateSum();
});
</script>

Я не лучший с Ajax, я сделал базовый пример того, что я считаю правильным путем:

Эта функция:

<script>
    // pass the total value over to the form: <input type="hidden" name="amount" value="getTheCost()">
    function getAndPassTheCost() {
        return $("#total").val();
    }
</script>

Получит значение из текстового поля ввода и передаст его в форму сообщения.

Эта функция:

<script>
    // pass the form values over and deal with them on the backend: <input type="hidden" name="custom" value="getTheFormValues()">
    function getTheFormValues() {
        return $("form").serialize();
    }
</script>   

Будет ли просто сериализовать все данные формы, которые я затем смогу проверить и обработать на бэкэнде.

Не усложнил ли я процесс?моя проблема в том, что я не могу передать эти данные в форму, которая затем отправляется через POST в скрипт PayPal, любая помощь в правильном направлении будет признательна.

1 Ответ

0 голосов
/ 31 марта 2019

Входы могут хранить только те строки, в которых они не могут хранить функции.Назначьте значения для формирования элементов управления методом .val().Функции getAndPassTheCost() и getTheFormValues() бесполезны.Если вам нужно сериализовать форму, сделайте это во время события отправки.Что касается сбора всех значений формы, это делается при отправке события - просто убедитесь, что любые значения, которые вы хотите отправить, имеют атрибут [name].

Демонстрация будет отправлена ​​на живой тестовый сервер -- ответ будет отображаться в нижнем фрейме.

function updateSum() {
  var total = 0;
  $(".sum:checked").each(function(i) {
    let sum = parseFloat($(this).val());
    total += sum;
  });
  $("#total, .total").val(total.toFixed(2));
}

$("input.sum").on('change', updateSum);
$('paypal_form').on('submit', function(e) {
  $(this).serialize();
});
.line.line.line {
  margin: -5px auto 5px
}

.img.img.img {
  margin: -40px auto 0 -70px;
}

.img.img.img:focus {
  outline: none
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
<main class='container'>
  <form class="form-horizontal" action="https://httpbin.org/post" method="post" id="paypal_form" target="response">

    <section class='form-row'>
      <fieldset class='form-group col'>
        <legend>Wraith SEO</legend>
        <input id="text" name="url" placeholder="site.com" type="text" class="form-control" required pattern='[a-z0-9]+?[.][a-z]{3,}'>
      </fieldset>
    </section>

    <hr class='line'>

    <section class='form-row'>
      <div class='form-group col'>
        <div class="form-check-inline">
          <label class="form-check-label">
  <input type="checkbox" class="sum form-check-input" name="metrics_1" value="1.00"> 1.00</label></div>

        <div class="form-check-inline">
          <label class="form-check-label">
  <input type="checkbox" class="sum form-check-input" name="metrics_2" value="1.00"> 1.00</label></div>

        <div class="form-check-inline">
          <label class="form-check-label">
  <input type="checkbox" class="sum form-check-input" name="metrics_3" value="1.00"> 1.00</label></div>

        <div class="form-check-inline">
          <label class="form-check-label">
  <input type="checkbox" class="sum form-check-input" name="metrics_4" value="1.00"> 1.00</label></div>

        <label for='total' class="label-control">Total: $ 
        <output id='total' value='0.00'> </output></label>

        <input class='total' name='total' type='hidden' value=''>
      </div>
    </section>

    <section class='form-row'>
      <fieldset class='form-group mb-4'>
        <input type="image" src="https://www.shareicon.net/data/128x128/2017/06/22/887585_logo_512x512.png" name="submit" alt="Make payments with PayPal - it's fast, free and secure!" class='float-right img'>

        <input type="hidden" name="cmd" value="_xclick">
        <input type="hidden" name="business" value="contact@site.co.uk">
        <input type="hidden" name="item_name" value="Wraith Metrics">
        <input type="hidden" name="item_number" value="1">
        <input type="hidden" name="currency_code" value="USD">
        <input type="hidden" name="return" value="https://www.wraithseo.com/custom-metrics-builder.php?paid=1">
        <input type="hidden" name="notify_url" value="https://www.wraithseo.com/gateway/ipn.php">

        <iframe name='response' width='70%' class='float-left'></iframe>
      </fieldset>
    </section>
  </form>

</main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...