Latest

Thursday, July 6, 2017

Ajax call fires success event but returns 201 error

Asked by: user2682025


I'm using Ajax on a Laravel project and I have a button that fires a function with two status error and success. but on both of them the success message returns.

Controller:

if ($user->balance < $total_paid) {
return response()->json(['responseText' => 'error'], 201);
} else {
return response()->json(['responseText' => 'success!'], 200);
}

Ajax function in the frontend:

<script type="text/javascript">
            function pay_with_ewallet()    { 
            $.ajax({
              url: "{!!URL::route('pay_with_ewallet')!!}",
              type: "post",
              data: {
                'OrderShipAddress':$('input[name=OrderShipAddress]').val(), 
                '_token': $('input[name=_token]').val(),
                'OrderEmail':$('input[name=OrderEmail]').val(),
                'city_id':$('select[name=city_id] :selected').val(),
                'OrderPhone':$('input[name=OrderPhone]').val(),
                'shipping_cost': @if (isset( $shipping_total )) {{ $shipping_total  }} @endif ,
                'order_total':@if (isset( $final_total )) {{ $final_total  }} @endif,
                },
                success: function(data) {
                    if (response == 'success') 
                        $("#myElem").show();
                        setTimeout(function() { $("#myElem").hide(); }, 10000);
                    else 
                        $("#myerror").show();
                        setTimeout(function() { $("#myerror").hide(); }, 10000);
                }​
            });
        }
    </script>

and the button:

<button href="" class="btn btn-danger pull-right" id="pay_with_ewallet-btn {{ $user->id }}" data-id="{{ $user->id }}" onclick="pay_with_ewallet('pay_with_ewallet{{ $user->id }}')">{{ trans('interface.pay_with_e_wallet') }}</button>

I tried whatever I can and a lot of research on the internet but was useless.



Source

No comments:

Post a Comment

Adbox