'Parameter is not sent to Laravel route in Ajax

I'm working with Laravel 5.8 and I wanted to apply a discount code system for my site.

So I tried sending data with Ajax like this:

$.ajax({
    type: 'POST',
    url: baseurl + 'discount/register',
    data: {
        coupon_code: finalDiscountValue,
        course_id: itemCourse,
    },
    dataType: "json",
    success: function (data) {
        if(data == 99) {
            swal("Wrong discount code");
        } else if (data == 130) {
            window.location.href = {!! json_encode(route('myCourseList')) !!}
        } else{
            window.location.href = {!! json_encode(route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id,'value'=>$data['cartValueDiscountedWithCode'] ?? ''])) !!}
        }
    }
});

Now my problem is $data['cartValueDiscountedWithCode'] which does not send to the defined route name.

And this is because $data is returned in Ajax and it's type is different from the other variable which is $item->cor_id and is Laravel based variable.

Here is how I return $data in the Controller:

public function registerWithDiscount()
    {
        $courseId = request('course_id');
        $findCourse = Course::find($courseId);
        $getCoursePrice = $findCourse->cor_price;

        if ( request('course_id') == null ) {
            return 97; // The input was empty
        }
        
        ...
        
        $data['cartValueDiscountedWithCode'] = $getCoursePrice - $value_discounted;
        $data['discountedPrice'] = $value_discounted;
        $data['coupon_id'] = $coupon->id;
        $data['coupon_name'] = $coupon->name;
                                                    
        if($data['discountedPrice'] >= $getCoursePrice){
            $this->registerDiscountFree($courseId,$data['cartValueDiscountedWithCode']);
            session()->flash('registrationMessage', 'Your registration is completed');  
            return 130; // if the discount code makes the course free
        }else{
            return $data; // if the remainer balance still needs to pay
        }
    }


Solution 1:[1]

You can try this:

let url = "{{ route('payCourseRegistrationWithDiscount',['course'=>$item->cor_id,'value'=>':cartValueDiscountedWithCode']) }}";
url = url.replace(':cartValueDiscountedWithCode', data.cartValueDiscountedWithCode);
window.location.href = url;

You can't pass the ajax response value like that. Instead, add a string inside route and later repalce with response value

Solution 2:[2]

what you will have to do is add the parameter as optional {value?}example

and then add the in blade

window.location.href = {{route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id]) }}}+'/'+data.cartValueDiscountedWithCode

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saroj Shrestha
Solution 2 Ajay2707