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.
<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.
/**
* 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.
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]
Optimize your Laravel Application for High Performance
Laravel has proved best PHP framework fo...Laravel Livewire Multiple File Upload Example
Larave Livewire is a full-stack web fram...How to secure phpMyAdmin
phpMyAdmin is free and open-source web a...How to Store Multiple Checkbox Value in Database in Laravel 8
In this article i will share with you ho...How to access laravel pagination protected object property?
Hello, everyone in this tutorials i will...