简体   繁体   English

单击按钮时如何使用 javascript 和 php 创建条纹产品

[英]How to create stripe product when click button using javascript and php

I'm Using PHP codes to create product in my products dashboard on stripe like this:我正在使用 PHP 代码在我的产品仪表板中创建产品,如下所示:

\Stripe\Stripe::setApiKey('sk_test_51JxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxJhn');
$product = \Stripe\Product::create([
  'name' => 'test',
]);

So what I'm trying to do here is whenever I click on submit button I must have the product on my stripe dashboard created:所以我在这里要做的是,每当我点击提交按钮时,我都必须在我的条纹仪表板上创建产品:

   <button id="submit-button" type="submit"  class="btn btn-primary" >Submit</button>
<script>
const btn = document.getElementById("submit-button");
btn.addEventListener("click", e => {
               e.preventDefault();
<?php
\Stripe\Stripe::setApiKey('sk_test_51JxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxJhn');
$product = \Stripe\Product::create([
  'name' => 'test',
]);
?>

               })



    </script>

But instead whenever the page is reloaded it created the product.但是,无论何时重新加载页面,它都会创建产品。 I only want the product created when the button is clicked !我只想要单击按钮时创建的产品!

Right now your PHP code runs whenever the page with the button is loaded because both the button code and the PHP code are in the same place, and you don't have any logic to prevent the product creation code from running.现在,只要加载带有按钮的页面,您的 PHP 代码就会运行,因为按钮代码和 PHP 代码都在同一位置,并且您没有任何逻辑来阻止产品创建代码运行。 You likely want to separate the two.您可能想将两者分开。

For example, in button.php you might have something like this:例如,在button.php中你可能有这样的东西:

<a href="create-product.php">Create Product</a>

And then in create-product.php you would have the code that creates the product.然后在create-product.php中,您将拥有创建产品的代码。

You can use JavaScript to do this without navigating to another page, which would look something like this:您可以使用 JavaScript 来执行此操作而无需导航到另一个页面,该页面看起来像这样:

<button id="submit-button" type="button" class="btn btn-primary">Submit</button>

<script>
const btn = document.getElementById("submit-button");
btn.addEventListener("click", e => {
  e.preventDefault();
  fetch('create-product.php').then( /* Handle response */ );
});
</script>

The code to create the product would also be in a separate file in this example.在此示例中,创建产品的代码也将位于单独的文件中。 See MDN's Fetch Usage Guide for more info.有关详细信息,请参阅MDN 的 Fetch 使用指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM