I am trying to learn Laravel9. For this I have Created a Controller, a model and blade view file. Below is my vatprofile.blade.php file code
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "/vatprofile",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>
And this is my Rout, Route::get('/vatprofile', [VatProfileController::class,'index']);
And Below is my Controller Function
public function index(){
return response()->json(['success'=>'Record is successfully added']);
}
It is not Giving Error, Not printing out any response. Only the Blank Page is Showing up. Can you Correct me Pls
CodePudding user response:
Please try this:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "{{ url('vatprofile') }}",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>
CodePudding user response:
First of all your URL seem to be wrong, With the laravel you must use the abolute URLs Please change it to
url: "{{ url('vatprofile') }}",
Also make sure you have added the CSRF token in the header, you can do it using the below code in your ready function before the ajax call.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
your final code should be
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "get",
url: "{{ url('vatprofile') }}",
dataType: "json",
success: function (response) {
alert(response);
}
});
});