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:
- I have a JavaScript function that triggers when a button is clicked.
- Inside this function, I'm calling a PHP function and passing a JavaScript variable as one of the parameters.
- The PHP function performs some processing and returns a value.
- Before and after the array, when I try to access the returned value, it shows as a string enclosed in double quotes.
- 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