Laravel Ajax return view with data example

When sending data over Ajax in Laravel, in response you want to update view. If you want to update view, you may want to return view with data.

In this article, I will share you how you can return view in Ajax request and push it to current view. Here is the example I have used in blade view to send data over Ajax.

Blade view

<script type="text/javascript">
    $(document).ready(function() {
        // apply discount
        $('body').on('click', '#discount-apply', function(event) {
            event.preventDefault();
            var code = $('#discount-code').val();
            $.ajax({
                type: "post",
                url: "{{ route('checkout.discountApply') }}",
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                data: {code: code},
                success: function (data) {
                    if (data.status == true) {
                        toastr.success(data.message);
                        $('body').find('.price-section').append(data.html);
                    } else {
                        toastr.error(data.message);
                    }
                },
            });
        });
    });
</script>

In this example, I send discount coupon to Ajax request. If the coupon code accepted, I return a view with all checkout calculation.

Here is the controller method

/**
 * validate coupon code
 *
 * @return mixed
 */
public function couponApply(Request $request)
{
    // valid json object
    $input = $request->only(['code']);

    $request_data = [
        'code' => 'required'
    ];

    $validator = Validator::make($input, $request_data);

    // json is null
    if ($validator->fails()) {
        return response()->json([
            'success' => false,
            'message' => 'Please input coupon code.',
        ]);
    }

    // here code to validate coupon code

    // coupon code applied success
    // apply coupon
    $applied_discount = AppliedDiscount::create([
        'discount_id' => $discount->id,
        'user_id' => $logged_user->id,
        'code' => $input['code'],
        'value' => $discount_value,
    ]);

    $applied_discount->save();

    if ($applied_discount == true) {
        $html = view('layouts.coupon', compact('applied_discount'))->render();

        return response()->json([
            'status' => true,
            'html' => $html,
            'message' => 'Coupon code applied successfully.',
        ]);
    } else {
        return response()->json([
            'status' => false,
            'message' => 'Something went wrong, please try again',
        ]);
    }
}

In the controller method, if the coupon code apply successfully, I reply HTML code with render() method and push it to view using jQuery.

This way, you can use Ajax to render HTML into blade view.

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment