I have a shopping cart page and button like
`<button class="purchase-button" data-courses-id="<?php echo $coursesID; ?>" onclick="Payment()">
</button>`
so when user click on it, the payment form will show and I want to get the ID of the product to display.
This is the js file:
`
function Payment() {
document.querySelector(".body-payment").style.display = "flex";
document.body.style.overflow = "hidden";
document.querySelectorAll(".purchase-button").forEach((button) => {
button.addEventListener("click", (event) => {
const courseID = button.getAttribute("data-courses-id");
const data = { courseID: courseID };
$.post("payment.php", data)
.done(function (response) {
console.log("Payment data sent successfully:", data);
})
.fail(function (error) {
console.error("Error sending payment data:", error);
});
});
});
}
`
The ajax work fine, it send data, but PHP dont:
`
if (isset($_POST['courseID'])) {}
else echo "Error";
`
I try print the SERVER and POST like:
`
print_r($POST);
`
and the output I got is array empty.
I guess that I dont have a form tag, and maybe the button is clicked twice. Please help me!
3
Answers
You can try this way
Check this without php code. And there is not sending, but logging in console:
I think problem is in js. When you click first time is nothing. In second time there is ‘5’. Third time it shows ‘5’ twice..
proper solution (after our comments bellow, just in your code delete function declaration and closing function tag and onclick="Payment()"):
Your code has some problems:
You put Payment() function to be executed on button click
Inside of this Payment() function you put another click listener which appends new click listener each time the button is clicked
php code of payment.php
if (isset($_POST[‘courseID’])) {}
else echo "Error";
does nothing if post variable courseID is set.
modified code:
html:
jQuery:
payment.php:
Console output:
Working repl.it repo