I have a form modal and I am trying to send data using ajax post method to the controller method 'store' via my blade file.
//// temp.blade.php file
<script type="text/javascript">
$(document).ready(function() {
$('#productForm').on('submit', function(e) {
let data = $('#productForm').serialize();
$.ajax({
url: "posts",
type: "POST",
datatype: "json",
data: {
"_token": "{{ csrf_token() }}",
data: data
},
success: function(response) //call back function
{
$('#respanel').html(response);
$('#productForm')[0].reset();
alert(response.message);
},
error: function(error) {
console.log(error);
alert(error.message);
}
});
});
});
</script>
route file
//// web.php file
Route::get('posts', [PostController::class, 'index']);
Route::post('posts', [PostController::class, 'store']);
controler class::
class PostController extends Controller
{
public function store(Request $request)
{
try {
return response()->json([
'status'=>200,
'message'=> $request->data
]);
} catch (Exception $e) {
return response()->json([
'status'=>200,
'message'=>$e->getMessage()
]);
}
}
}
When I send data as name = 'test' and detail = 'dummy-details' from my blade file, the controller store method show response as
id=&name=test&detail=dummy-details
but when I change the return response message variable to
return response()->json([
'status'=>200,
'message'=> $request->name // or $request->input('name')
]);
the response message is null
and when I do
return response()->json([
'status'=>200,
'message'=> $request->all()
]);
it shows [object Object]
What is the problem with the data format? How to get the data from the request variable? Thank You!!!
axiosor the built-infetch) . jQuery ajax was built for a different era of the internet and doing something as simple as sending a JSON request is actually more complicated.