Reputation: 852
I cannot understand this:
I have a Laravel form. In the controller, I set up the consideration that the form might store data via ajax, and I have also put a fallback non-ajax for another part of the site, where ajax is not used:
public function store(Requests\EntryRequest $request) {
$journal = new Article($request->all());
if ( Request::ajax() ) {
Auth::user()->articles()->save($journal);
return response(['msg' => 'Daily entry saved', 'status' => 'success']);
} else {
Auth::user()->articles()->save($journal);
return redirect('home')->with('message', 'Daily entry saved');
}
}
So far so good. My form contains a checkbox, and also a hidden input in order to help sending a value with the form if the user doesn´t touch the checkbox (I remove the hidden value later on if the real checkbox is checked)
{!! Form::hidden('doctor', '0', ['type'=>'hidden', 'id'=>'drhelp'] ) !!}
{!! Form::checkbox('doctor', '1', false , ['class' => 'checkbox', 'data-toggle'=>'toggle', 'data-onstyle'=>'success', 'id'=>'drcheck']) !!}
And the form is being sent like this, nothing special:
$.ajax({
type: "POST",
url: '/articles/',
data: form.serialize(),
success: function( msg ) {
//do things after success
}
});
My question: Why does the form works through Ajax JUST when I manually change the checkbox. For instance, it opens unchecked, so if I want to post it unchecked, I must check it and uncheck it again. If I don´t touch it, the form just goes via regular submit.
And yet, if I interact with the checkbox, the form goes through Ajax POST. What is the problem here?
Thanks so much
Upvotes: 0
Views: 893
Reputation: 342
my better way to handle that is to add default value to check box from migration
$table->boolean('doctor')->default(false);
then you dont have to add hidden input and this will be enough
{!! Form::checkbox('doctor', true, false , ['class' => 'checkbox', 'data-toggle'=>'toggle', 'data-onstyle'=>'success', 'id'=>'drcheck']) !!}
Upvotes: 1