-1

I have got a script in JS and there is a function with the json response. I want to use the response (the value) and use in the php function (instead of hardcoding it with the number).

To be exact, I want to use the value *totalAmount * from the getTotal() function and use it in the $ParArray as "amount" in php (insetad of hardcoding).

How can I do this? Any hints will be helpfull! :)

<?php include 'includes/session.php'; ?>
<?php include 'includes/scripts.php'; ?>
    <script>
        var total = 0;
        var city = $('#city').val();
        $(function() {

       (...)

        function getTotal() {
            $.ajax({
                type: 'POST',
                url: 'total.php',
                dataType: 'json',
                data: function(response) {
                    totalAmount = response; 
                 
                }
            });
        }


    </script>

<?php

$ParArray = array(

    "amount" =>  "55",
    "currency" => "USD",
    "type" => "0",
);
(...)
?>
  • Does this answer your question? [How do I pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-do-i-pass-javascript-variables-to-php) – Nico Haase Apr 08 '23 at 11:29

1 Answers1

1

PHP codes are executed before JS. As a result, it cannot be done in one script.

To do this, you can send the totalAmount value to a PHP script using Ajax

function getTotal() {
    $.ajax({
        type: 'POST',
        url: 'total.php',
        dataType: 'json',
        success: function(response) {
             calculateResult(response); 
             
        }
    });
}


function calculateResult(value){
    $.ajax({
        type: 'POST',
        url: 'calculate.php',
        data: {'value':value},
        dataType: 'json',
        success: function(response) {
             ...
        }
    });
}

new file(calculate.php):

<?php
$ParArray = array(

    "amount" =>  $_POST['value'],
    "currency" => "USD",
    "type" => "0",
);
Kamyar Safari
  • 420
  • 2
  • 9