Move e.preventDefault(); up to the first thing that happens when you enter the method.
Laravel 5.1 - can't prevent page redirect on Ajax call
I'm trying to make an ajax call on a form submit, and prevent the page redirect. I was following the 'Everything Else' lesson but can't figure out why I'm getting redirected on the form submit.
the js
(function () {
var submitAjaxRequest = function (e) {
var form = $(this);
var method = form.find['input[name="_method"]'].val() || 'POST';
$ajax({
type: method,
url: form.prop('action'),
data: form.serialize()
});
e.preventDefault();
};
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
the form view:
{!! Form::open(['data-remote', 'method' => 'PATCH', 'url' => 'costs/' . $invoice->id]) !!}
@foreach($invoice->cost_misc()->get() as $cost_misc)
<div class="cost-container">
<div class="form-group" style="float: left;">
{!! Form::label('cost_misc_name', 'Megnevezés:') !!}
{!! Form::text('cost_misc_name[]', $cost_misc->name, ['class' => 'form-control' ]) !!}
</div>
<div class="form-group" style="float: left;">
{!! Form::label('cost_misc_value', 'Érték:') !!}
{!! Form::input('number', 'cost_misc_value[]', $cost_misc->value, ['class' =>
'form-control']) !!}
</div>
<a href="#" class="btn btn-danger btn-remove"
style="float: left; margin: 25px 0 0 10px;">-</a>
<div style="clear: both;"></div>
</div>
@endforeach
<a href="#" class="btn btn-info btn-add-more-cost-misc" style="clear: both;">+</a>
<hr/>
{!! Form::hidden('type', 'cost_misc') !!}
{!! Form::submit('Mentés', ['class' => 'btn btn-success form-control' ]) !!}
{!! Form::close() !!}
the controller:
public function update(CostRequest $request, $id)
{
$invoice = Invoice::find($id);
$this->createCosts($request, $invoice);
$this->updateInvoiceState($invoice);
}
In the controller called functions I don't have and redirect or view returns. I tried to remove the Validation and get the input data 'manually' but no luck either. Even if I use controller action in the form the same redirect happens.
As I'm a Laravel rookie I would welcome any help!
As it turns out it was a syntax error in my JS file. I had two typos.
I had square brackets instead of parentheses for the find method.
var method = form.find['input[name="_method"]'].val() || 'POST';
I didn't include the . in the $.ajax call
$ajax({
type: method,
url: form.prop('action'),
data: form.serialize()
});
Apart from this the original code was working perfectly, but all the given answers in this thread work as well. I spent 1 day searching for this error, at least I learned a lot about Ajax. Thank you for the help everybody.
Please or to participate in this conversation.