Search code examples
phpajaxresponse

Issue redirecting payment status from AJAX to PHP


Am working on a payment integration gateway with PHP whereby am listening for a response from the gateway which is either 1 or 2 or 0 . On success, I want to redirect any of the string to AJAX success which aint working as expected

PHP Code

        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 code where I want to listen for the response

<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>

Solution

  • change return statements to echo statements then you can use those values in front-end

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

    and it is better if you use json object as response. it will be easy to ready in front-end.

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