首页 > 解决方案 > 将支付状态从 AJAX 重定向到 PHP 的问题

问题描述

我正在使用 PHP 开发一个支付集成网关,其中正在监听来自网关的响应,即 1 或 2 或 0 。成功后,我想将任何字符串重定向到 AJAX 成功,它不能按预期工作

PHP 代码

        for($try=1; $try<=3; $try++) {
            sleep(15);
            $payStat = $this->global_Curl($data, 'api/payment/status')->data;
            //dd($payStat);
            //Check if staus is zero meaning not paid
            if ($payStat->status === 0) {
                return 'notPaid';
            }
            //check if status is 2 meaning cancelled
            elseif ($payStat->status === 2) {
                return 'Cancelled';
            }
            //check if status is 1 meaning paid
            elseif ($payStat->status === 1) {
                return 'Paid';
            }
        }

我想监听响应的 AJAX 代码

<script type="text/javascript">
  $('.mpesa').on('click', function () {
    //alert('clicked');
    //Adds Class to the page when it loads
    $('.PAY').addClass("loading");
    //Gets the MPESA type
    var type = $('.mpesa').prop('id');
    var quote = $('#quote').val();
    var phone = $('#phone').val();
    //Converts to a JSON object
    var type ={
      'type': type,
      'quote' : quote,
      'phone' : phone,
    };

    //console.log(type);

    $.ajax({
        //Contains controller of payment
        type: 'POST',
        url: 'paymentFinal',
        data: JSON.stringify(type),
        contentType: 'application/json',
        dataType: "json",
        success: function success(response) {
            //Log the reponse from PHP code
            console.log(response);
        },
        error: function error(data) {
              //alert('Error');
        }
    });
  });
</script>

标签: phpajaxresponse

解决方案


return语句更改为echo语句,然后您可以在前端使用这些值

if ($payStat->status === 0) {
    echo 'notPaid';
    return; // if you need to exit
}

如果您使用 json 对象作为响应,那就更好了。很容易在前端做好准备。

if ($payStat->status === 0) {
    echo ['status' => 'notPaid'];
    return; // if you need to exit
}

推荐阅读