1

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!

19
  • 1
    what do you see in the console? it would be better to console.log(response) instead of data since you are trying to confirm the response from PHP, not the data you passed to PHP Commented Aug 23, 2024 at 7:56
  • 1
    Maybe the ajax dont really send data to PHP...if you use your browser's Network tool, you can see the AJAX request (you must open the tool before you send the request, though). You can click on the ajax request, and see the Payload data, so you can confirm exactly what it sends to PHP. You can also click on the Response data in the same area, to see exactly what PHP sends back in response to that particular request. (So actually you don't even need the console to debug it really) Commented Aug 23, 2024 at 8:20
  • 1
    Sounds like you are making two different requests here - first the AJAX request, and then you (re-)load your payment form separately? Of course that won't work, the POST data is only available when you are handling the AJAX request, but not in a totally independent request that has nothing whatsoever to do with your AJAX request to begin with. Commented Aug 23, 2024 at 8:29
  • 1
    You do realize, that $POST does probably not exist at all, it should be $_POST ... Commented Aug 23, 2024 at 8:34
  • 1
    is shown in the payment form (payment.php file)...so you mean, in the browser window and not in the console or network tool? Well in that case it sounds like it didn't come from an ajax request at all. Which would explain why it doesn't contain the data AJAX was sending. Have you looked in your network tool yet to see what's going on? Are you ever seeing that console.log("Payment data sent successfully:", data); message in the console, or not? I must say there are a lot of comments here asking for info and you are replying with relatively vague information, which isn't helping anyone. Commented Aug 23, 2024 at 8:36

3 Answers 3

1

Your code has some problems:

  1. You put Payment() function to be executed on button click

  2. Inside of this Payment() function you put another click listener which appends new click listener each time the button is clicked

  3. php code of payment.php

    if (isset($_POST['courseID'])) {} else echo "Error";

does nothing if post variable courseID is set.

modified code:

html:

<button class="purchase-button" data-courses-id="<?=$coursesID?>" onclick="Payment(this)">
          purchase
      </button>

jQuery:

function Payment(button) {

      $(".body-payment").css("display", "flex");
      $("body").css("overflow", "hidden");
      
      const courseID = $(button).attr("data-courses-id");
      const data = { courseID: courseID };

      $.post("payment.php", data)
        .done(function(response) {
          console.log("Payment data sent successfully! Server response: ", response);
        })
        .fail(function(error) {
          console.error("Error sending payment data:", error);
        });
    }

payment.php:

<?php
if (isset($_POST['courseID'])) {
  echo 'I received the following: ' . $_POST['courseID'];
}
else echo "Error";
?>

Console output:

Payment data sent successfully! Server response:  I received the following: 89

Working repl.it repo

Sign up to request clarification or add additional context in comments.

Comments

1

Check this without php code. And there is not sending, but logging in console:

<!DOCTYPE html>
    <html>
    <head>
      <title>tytuł</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
    <button class="purchase-button" data-courses-id="5" onclick="Payment()">button
    </button>
    </body>
    <script type="text/javascript">
    function Payment() {
      document.querySelectorAll(".purchase-button").forEach((button) => {
        button.addEventListener("click", (event) => {
          const courseID = button.getAttribute("data-courses-id");
          const data = { courseID: courseID };
          console.log(data);
        });
      });
    }
    </script>
    </html>

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()"):

<!DOCTYPE html>
    <html>
    <head>
      <title>tytuł</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
    <button class="purchase-button" data-courses-id="5">button
    </button>
    </body>
    <script type="text/javascript">
      document.querySelectorAll(".purchase-button").forEach((button) => {
        button.addEventListener("click", (event) => {
          const courseID = button.getAttribute("data-courses-id");
          const data = { courseID: courseID };
          console.log(data);
        });
      });
    </script>
    </html>

2 Comments

just like you said, maybe its affected by the while loop, but I put the file in the bottom of the body tag
i think I know where is problem. You put adding listener (addEventListener) in the function. And the code adds the listener only after function is started. And again, again.. Just add listener without function payment (delete function Payment () { and closing tag }).
-1

You can try this way

  • Add the event listener when the DOM is ready, rather than waiting for the 'payment' function to be called, move the event listener outside the 'payment' function.
  • Trigger the 'payment' function directly inside the event listener

1 Comment

If you want to change the approach OP is trying you need to at least add more supporting information and code about your idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.