I'm Using PHP codes to create product in my products dashboard on stripe like this :
\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. You likely want to separate the two.
For example, in button.php you might have something like this:
<a href="create-product.php">Create Product</a>
And then in create-product.php you would have the code that creates the product.
You can use JavaScript to do this without navigating to another page, which would look something like this:
<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.