Reputation:
I have a form in which I user can insert multiple inputs fields and save to database using ajax Here are the inputs,
I'm trying to send a serialized form to my database. My question is that when I serialize the form, use JQuery to attach it to a hidden input field, and then send the the form and some other information to the database, the rest of the information is reaching the database but I still have a blank in where the serialized form is. If anyone could point out where I went wrong and/or explain how this should be done I'd be very grateful! Thank you very much!
blade
<form method="post" id="form-job-store">
<input type="hidden" name="url" value="{{ route('job.store') }}">
@csrf
<div class="row">
<div class="col-md-6 mb-3">
<div class="col-md-6 mb-3">
<label for="history">history</label>
<input type="text" class="form-control" id="history" name="history">
</div>
<div class="col-md-6 mb-3">
<label for="post_title">post_title</label>
<input type="text" class="form-control" id="post_title" name="post_title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<button type="submit" class="btn btn-success" id="btn-job-submit"><i class="fas fa-plus fa-xs"></i> Save</button>
</div>
</div>
<form>
script
$(document).ready(function () {
$('#btn-job-submit').on('click', function (event) {
event.preventDefault();
var formData = new FormData($('#form-job-store')[0]);
let url = $('#form-job-store :input')[0].getAttribute('value');
$.ajax({
type: 'POST',
url,
data: $(formData).serialize(),
success: function (data) {
alert(data);
},
});
});
});
web.php
Route::resource('job', 'JobController');
JobController.php
public function store(Request $request)
{
$job = Job::create([
'user_id' => auth()->id(),
'post_title' => $request->post_title,
'history' => $request->history,
]);
return response()->json($job);
}
Upvotes: 0
Views: 2362
Reputation: 5270
You have to use like this
$(document).ready(function(){
$('#btn-job-submit').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'{{route('job.store')}}',
method:"POST",
data:new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
}
})
})
})
Upvotes: 1