joh
joh

Reputation: 238

Submitting a form with ajax and laravel

I'm trying to add product to the database with Ajax without refreshing the page and send the data to the database but I get an error Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. on console. How can I submit the form without refreshing the page?

Blade

 <form method="POST" role="form" enctype="multipart/form-data">
        {{csrf_field()}}

           <label for="pro_name">Name</label>
           <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

           <label  for="category_id">Choose Category</label>
           <select name="category_name" id="category_name">
           <option value=""> --Select Category -- </option>
           @foreach ($categoryname_array as
             $data)
             <option value="{{ $data->name }}"  >{{$data->name}}</option>
             @endforeach
           </select>

           <label for="photos">Choose 5 Images</label>
           <input  "multiple="multiple" name="photos[]" type="file">

           <button type="button" onclick = "submitThisForm({{Auth::user()->id}})" class="btn btn-primary">Submit</button>

    </form> 

Ajax

<script>
function submitThisForm(id){
    let url = "{{ route('product.store', ['id' => ':id']) }}".replace(':id', id);
    $.ajax( {
        url: url,
        type: 'POST',
        data: new FormData( this ),
        processData: false,
        contentType: false,
        success: function(result){
            console.log(result);
        }
    } );
    e.preventDefault();


}
</script>

Route

 Route::post('seller/product', 'ProductController@store')->name('product.store');

Upvotes: 2

Views: 4039

Answers (2)

porloscerros Ψ
porloscerros Ψ

Reputation: 5098

I think you're overcomplicating things.

First, your route does not expect any parameters.

Route::post('seller/product', 'ProductController@store')->name('product.store');

So you don't need to pass it on.

{{ route('product.store', ['id' => ':id']) }} // remove , ['id' => ':id']

Then, since you are using jquery, you can handle the ajax call on the submit method of the form.

$('form').on('submit', function (e) {
    e.preventDefault(); // prevent the form submit
    var url = '{{ route('product.store' }}';
    // create the FormData object from the form context (this),
    // that will be present, since it is a form event
    var formData = new FormData(this); 
    // build the ajax call
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        success: function (response) {
            // handle success response
            console.log(response.data);
        },
        error: function (response) {
            // handle error response
            console.log(response.data);
        },
        contentType: false,
        processData: false
    });
})

In your form you will not need the onclick event on the button..

<form method="POST" role="form" enctype="multipart/form-data">
    {{csrf_field()}}

    <label for="pro_name">Name</label>
    <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

    <label  for="category_id">Choose Category</label>
    <select name="category_name" id="category_name">
    <option value=""> --Select Category -- </option>
    @foreach ($categoryname_array as $data)
        <option value="{{ $data->name }}"  >{{$data->name}}</option>
    @endforeach
    </select>

    <label for="photos">Choose 5 Images</label>
    <input  "multiple="multiple" name="photos[]" type="file">

    <button type="button" class="btn btn-primary">Submit</button>

</form> 

Upvotes: 3

BCM
BCM

Reputation: 675

Try this.

<form id="myForm" method="POST" role="form" enctype="multipart/form-data">

<script>
function submitThisForm(id){
    let url = "{{ route('product.store', ['id' => ':id']) }}".replace(':id', id);
    var form_data = new FormData(document.getElementById("myForm"));
    $.ajax( {
        url: url,
        type: 'POST',
        data: form_data,
        processData: false,
        contentType: false,
        success: function(result){
            console.log(result);
        }
    } );
    e.preventDefault();


}
</script>

Upvotes: 0

Related Questions