skip to Main Content
$(".save_form_email").on('click', function() {
    var pocet = $('#save__cena').val();
  console.table(pocet);
  $.ajax({
    url: '/modules/mod_custom_extended/tmpl/default.php',
    type: 'POST',
    data: {
      pocet: pocet
    },
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function(response) {
      console.table(response);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log('AJAX request failed: ' + textStatus + ', ' + errorThrown);
    }
  });

});

This is the PHP

<?php
if (isset($_POST['pocet'])) {
  $temp_pocet = $_POST['pocet'];
}
?>

This is my attempt to send value of html input field with id "save__cena" to the php so i can later use this price to send it to stripe.
Currently i have nothing in php variable temp_pocet

2

Answers


  1. When you send JSON data using an ajax request to php, the data is not accessible in the $_POST superglobal. You need to read from php://input instead like so:

    <?php
    $form_data = json_decode(file_get_contents('php://input'));
    

    $_POST only works with data that has the Content-Type set to application/x-www-form-urlencoded or multipart/form-data, not application/json.

    Additional info: this stack overflow answer

    EDIT

    If you also plan on returning a json response from the php script, then you should move the code that processes the ajax request to a separate php file that is not mixed with any html code. This is to prevent html characters from being sent along with the json response and causing it to become corrupted.

    Oh and you should also change your content-type header to application/json

    Login or Signup to reply.
  2. Try this

    $(".save_form_email").on('click', function() {
            var pocet = $('#save__cena').val();
          console.table(pocet);
          $.ajax({
            url: '/modules/mod_custom_extended/tmpl/default.php',
            type: 'POST',
            data: {
              // I change this line
              // pocet: pocet -> Original
              "pocet": pocet // updated
            },
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function(response) {
              console.table(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed: ' + textStatus + ', ' + errorThrown);
            }
          });
        
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search