Ajax call to get the value selected from a HTML Select Option

Posted 5 months ago by bobmyles

On a dropdown option, I would like to listen in and get the value of the option selected by the user.

Then I would like to pass this value to a PHP variable for use in the later part of the blade view PHP script.

I do not want to reload the page hence from the online look, I found ajax to be the only possible way.

I tried to implement as shown below but hitting a snag as the page loads on submit.

Even better is it possible to have a select option drop down that you get the selected value without submit?

My select option code:

    <form id="myForm">
        <div class="button dropdown">
          <select name="languageSelected" required="required" id="languageselector" onChange='showSelected(this.value)'>
            <option value="">Pick A language</option>
            @foreach($reviewForm_language as $lang)
             <option value="{{$lang->id}}">{{$lang->name}}</option>
            @endforeach
          </select>
        </div>
        <input id="ajaxSubmit" type="submit" value="Select"/>
    </form>

My JS code:

  <script>
       jQuery(document).ready(function(){
          jQuery('#ajaxSubmit').click(function(e){
             e.preventDefault();
             $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                }
            });
             jQuery.ajax({
                url: "{{ url('#') }}",
                method: 'post',
                data: {
                   id: jQuery('#languageSelected').val(),

                },
                success: function(result){
                   jQuery('.alert').show();
                   jQuery('.alert').html(result.success);
                }});
             });
          });
    </script>

On reload I can get the value as a GET request as below; however, I do not want to reload the page but for some reasons it does reload.

<?php
    $langId = request()->get('languageSelected');
 ?>

Anyone?

Please sign in or create an account to participate in this conversation.