bohdan baida bohdan baida - 3 months ago 31
jQuery Question

Laravel 5.4 AJAX form post routing 404 error

I am working on my form submitting with AJAX. Form was working before with just regular method without AJAX. All routes is good, and form working properly. Now I found need in AJAX functions to submit my form. I've wrote script as usual for AJAX submitting.

Here is my form script:

<div class="onpage-sold-input">
{!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button','method'=>'POST']) !!}
{!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
<input type="hidden" name="part_id" value="{{ $inventory->id }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{!! Form::button('Sold', ['class' => 'btn btn-sm btn-success', 'id'=>'sold-button','type'=>'submit']) !!}
{!! Form::close() !!}

Hare is AJAX script:

headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')

$('#sold-button').on('click', function (e) {

var form = $('#search-sold-button'),
data = form.serialize(),
ajax_url = 'sold/sold',
alert_section = $('.alert-section');

$.post(ajax_url, data, function (resp) {
setTimeout(function () {
}, 3000)

Here is route:

Route::post('/sold/sold',['uses'=>'PriceController@sold', 'as'=>'sold.sold']);

And this is the error that I am getting in console:

POST http://localhost/backend_master/public/inventory/sold/sold 404 (Not Found)

I am not sure what i am doing wrong here.

Answer Source

You need to change this line:
ajax_url = 'sold/sold',

by this:
ajax_url = form.attr('action'),