-1

I want to submit the form when I select an option from select option but I don't want the page to reload after doing that. I used the e.preventDefaut() but the form stops saving to the database. PS: it was saving perfectly before adding the preventDefault but the page does reload.

Here is my code for the form:-

<form action="{{route('course.add')}}" method="POST"  > 
    @csrf

    <div class="aa">
        <div class="dd">

                <input type='checkbox' id='HiddenCheck{{$course->id}}' >
                <input class='red' id = "b{{$course->id}}"  onclick="showComboBox({{$course->id}})" >

                <label class="class_name" value ="{{$course->id}}" >{{$course->courseNumber}}</label>
                <input hidden type="number" value="{{$course->id}}"  name ="course"/>
        </div>

        <div class="select-style" id="check{{$course->id}}" hidden >
            <select name="a" id="season" >
            <option value="" selected disabled hidden>Taken on </option>
            <option value="Summer">Summer</option>
            <option value="Fall">Fall</option>
            <option value="Winter">Winter</option>
            <option value="Spring">Spring</option>
            </select>
        </div>
    </div>
</from> 

and here is my Ajax code to submit the form:-

$('#season').on('change', function(e) {
    e.preventDefault() ;
    $(this).closest('form').submit();

});

I was expecting the form to be submitted and my data added to the database without reloading the page. But when I added the preventDefaut() the data stop saving in the database.

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52
Elin
  • 105
  • 1
  • 7

2 Answers2

1

You can submit the form with ajax.

First solution - With onChange submit

Assuming you have a submit button with id btn-submit.

Add a id to the form, like my-form.

$(".select-style").on('change', function(){
    $.ajax({
        url: 'your-route-here',
        method: 'post',
        data: {
            $("#my-form").serialize(),
        },
        success: function(response){
            alert('ok');
        }
    });
});

Second one - With button submit

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

  • With ajax form:
$("#theFormId").ajaxForm({url: 'server.php', type: 'post'});

or

$("#theFormId").ajaxSubmit({url: 'server.php', type: 'post'});

ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

Hope it helps.

Mateus Junges
  • 2,559
  • 1
  • 12
  • 24
1

Try using ajax post request

$('#season').on('change', function(e){
 e.preventDefault() ;
     var url = e.target.action  // get the target
     var formData = $(this).serialize() // get form data
     $.post(url, formData, function (response) { // send; response.data will be what is returned
         alert('data sent')
     })
 });

  • I tried it but it doesn't work, even if I remove the preventDefault still not working – Elin Jun 22 '19 at 08:11