I've got a working form that submits to a database from an HTML form using Laravel Collective that submits to my Controller, and it works fine.
I want to submit it without a page reload, so I'm submitting the data with AJAX.
I've got it working, and it's writing to the db, but I can't get the controller to return the response to the page on success.
The following is my script:
SCRIPT:
$(document).ready(function(){
$("#msg").hide();
$("#submit").click(function() {
$("#msg").show();
var name = $("#recipeName").val();
var description = $("#recipeDescription").val();
var token = $("#token").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: "name="+name+"&description="+description,
dataType:'json',
url: "{{ route('recipes.store') }}",
success:function(data){
$("#msg").html("Recipe Saved");
$("#msg").fadeOut(2000);
}
});
})
})
HTML:
<div class="row">
<div class="col">
<p class="alert alert-success" id="msg"></p>
</div>
</div>
<div class="row">
<div class="col">
<!-- Start Form -->
<input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
<div class="form-group">
<label for="recipeName">Recipe name:</label>
<input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="recipeDescription">Recipe Description:</label>
<textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
<!-- End Form -->
</div>
</div>
CONTROLLER:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'description' => 'required'
]);
$recipe = new Recipe;
$recipe->name = $request->name;
$recipe->description = $request->description;
$recipe->user_id = auth()->user()->id;
$recipe->save();
return Response::json(array(
'success' => true,
'data' => $data
));
}
I can't workout what it is that I'm missing.
I'm learning AJAX on the fly (I'm learning all of it on the fly if I'm honest!), but as I say, it's writing to the db successfully, just need to notify the user of it.