[ad_1]
i am using ajax laravel i am trying to store the info but when i click on the submit button to store, the console returns an error 500 (Internal Server Error) on line that cocntains $.ajax
i don’t know why i wrote everything correctly please help
and here is my code
my route
Route::resource('products',App\Http\Controllers\ProductController::class);
my form and ajax code
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add new Product</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form enctype="multipart/form-data" method="POST" id="productform">
@csrf
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="">image</label>
<input type="file" name="image" class="form-control">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#productform').submit(function(e){
e.preventDefault();
var name = $("input[name="name"]").val();
var image = $("input[name="image"]").val();
var _token = $("input[name="token"]").val();
$.ajax({ //this is the consoles error line
url:"/products",
type : "POST",
data:{
name:name,
image:image,
_token:'{!! csrf_token() !!}',
},
dataType:'json',
success:function(response){
console.log(response);
}
});
});
});
</script>
my controller store method
public function store(Request $request)
{
$file = $request->file('image');
$file_name = time().'_'.$file->getClientOriginalName();
$upload = move_uploaded_file($file_name,public_path('files/'));
// $upload = $file->storeAs(public_path($path), $file_name, 'public');
if($upload){
$product = Product::insert([
'name'=>$request->name,
'image'=>$file_name,
]);
}
return response()->json($product);
}
[ad_2]