0

I'm facing an issue when trying to pass a JavaScript variable as a parameter to a PHP function and handling the returned value. Here's the scenario:

  1. I have a JavaScript function that triggers when a button is clicked.
  2. Inside this function, I'm calling a PHP function and passing a JavaScript variable as one of the parameters.
  3. The PHP function performs some processing and returns a value.
  4. Before and after the array, when I try to access the returned value, it shows as a string enclosed in double quotes.
  5. However, when I check the value inside the array, it returns null. Here's an example of my code:
function expresspay($phone, $amount, $reference, $description, $remark) {
    $endpoint = "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest";
    $timestamp = date("YmdHis");
    $password = base64_encode(tourmaster_get_option('payment', 'mpesa-shortcode', '').tourmaster_get_option('payment', 'mpesa-passkey', '').$timestamp);
    $curl_post_data = array(
        "BusinessShortCode" => tourmaster_get_option('payment', 'mpesa-shortcode', ''),
        "Password" => $password,
        "Timestamp" => $timestamp,
        "TransactionType" => tourmaster_get_option('payment', 'mpesa-live-mode', 'CustomerPayBillOnline'),
        "Amount" => round($amount),
        "PartyA" => $phone,
        "PartyB" => tourmaster_get_option('payment', 'mpesa-till', ''),
        "PhoneNumber" => $phone,
        "CallBackURL" => 'https://wildsafaris.co.ke/?tourmaster-payment',
        "AccountReference" => $reference,
        "TransactionDesc" => $description,
        "Remark" => $remark,
    );

    $token = token();
    $header = array("Content-Type:application/json", "Authorization:Bearer ".$token);

    return curlfunction($endpoint, $header, 'POST', json_encode($curl_post_data));
} ?
>
<
script type = "text/javascript" >
    (function($) {
        $('#pay').click(function() {
            function formatPhoneNumber(phoneNumber) {
                phoneNumber = phoneNumber.replace(/\s/g, '');
                if (/^0\d{9}$/.test(phoneNumber)) {
                    return '254' + phoneNumber.substr(1);
                }
                if (/^[1-9]\d{8}$/.test(phoneNumber)) {
                    return '254' + phoneNumber;
                }
                if (/^254\d{9}$/.test(phoneNumber)) {
                    return phoneNumber;
                }
                return 'Invalid phone number';
            }
            var phone = $('#phone').val();
            var item_name = $('#item_name').val();
            var amount = $('#amount').val();
            var jsonString = JSON.stringify( < ? php echo expresspay("' + phone + '", ' + amount + ', item_name, "", "REMARKS"); ? > );
            alert(jsonString);
        });
    })(jQuery); <
/script>

I tried to pass phone number from html input to javascript variable to php function and I am getting empty value in array yet outside array it contains a value with double quote

KIPKOECH
  • 19
  • 5
  • 1
    #2 doesn't do what you could think it does. PHP is executed before the page exists at a browser. – Teemu May 17 '23 at 08:31
  • @Teemu No. I have enclosed my script inside document is ready still empty. – KIPKOECH May 17 '23 at 08:45
  • 1
    I love when people start to argue. Please read the linked post carefully. – Teemu May 17 '23 at 08:46
  • 1
    `I have enclosed my script inside document is ready`...well you haven't actually. But even if you had, that only applies to JavaScript code, not PHP code. Have a look at the generated source code of your page in the browser (you can use Ctrl+U in most browser to do that), and see what's actually on the `var jsonString = JSON.stringify...` line. Then you'll realise that what you're doing makes no sense because a) PHP code executes on the server _before_ the page reaches the browser, and the _output_ of the PHP code is sent to the browser, and b) JS variables can't be used inside a PHP statement – ADyson May 17 '23 at 09:26
  • P.S. If you really did write `< ? php` with all those spaces in, that doesn't make an executable PHP block anyway: it would need to be `` would need to be `?>` – ADyson May 17 '23 at 09:26
  • 1
    @Teemu true. I just quoted their comment, didn't actually look closely at the code - my bad! So it's not like the JS is even waiting for anything anyway. I've amended my reply. – ADyson May 17 '23 at 09:29
  • @KIPKOECH Bottom line: The web is a stateless, disconnected, client-server architecture. When the browser makes a HTTP request to the server, it starts the PHP code running. When the PHP code stops running, the finished output is delivered to the browser as the next page. To make the PHP do something more after that, you need to send another HTTP request to the server to start the process again. To trigger that, you can use AJAX (to avoid refreshing the whole page), or submit a form, or cause a navigation (via a hyperlink or Javascript) to a new URL which may include querystring parameters. – ADyson May 17 '23 at 09:34

0 Answers0