How to return view with data in Laravel 8 using Ajax

  13279 views   1 year ago Laravel

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) {
            var code = $('#discount-code').val();
                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) {
                    } else {

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,


    if ($applied_discount == true) {
        $html = view('', 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]