Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bobmyles's avatar

How to get the HTML select option in AJAX

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 HTML code:

<form id="myForm">
    <div class="button dropdown">
      <select name="languageSelected" required="required" id="languageselector">
        <option value="">Select the 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>

The JavaScript code:

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="

crossorigin="anonymous">

<script>    
jQuery('#languageselector').on('change', function(){      

    jQuery.ajax({
      url: "{{ url('/selected/id') }}",
      method: 'post',
      data: {
         id: $(this).val(),
      },
      success: function(result){
         jQuery('.alert').show();
         jQuery('.alert').html(result.success);
      }
    });

});

The PHP code to pick the selected language id

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

My route code;

Route::post('/selected/languageId', 'ProfileController@selectedLangId');

My controller Code;

public function selectedLangId(Request $request)
{
    return response()->json(['success'=> $request->id]);
}

I am learning AJAX, and for some reasons the page loads. Anyone kindly guide me?

0 likes
6 replies
Cronix's avatar

A few things.

Your urls don't match for one. Ajax request is going to /selected/id, but route is set up to respond to /selected/languageId.

$langId = request()->get('languageSelected');
  1. You're not sending the request with get method, you're using post so get() won't retrieve it
  2. You don't have a parameter named languageSelected that you're sending with your ajax request. The only parameter you send is id
bobmyles's avatar

@CRONIX - Hello @cronix I did test with your set up but still the page reloads... I changed the url to test if the AJax request was hitting the URL or if I was getting a 404. But still nothing

Cronix's avatar

Page reloads....when you do what exactly?

I would expect it to reload if you submit the form with your submit button, because that has nothing to do with your ajax which is only setup to listen to the change event of the select element. You don't prevent normal form submission, so it sends. And since you don't have an action or method for your <form> markup, it defaults to sending to the current url using a get request (which would look like a page reload). I would not expect it when changing your select dropdown. That should trigger the ajax request.

Also open up your browsers dev tools and watch the network tab for your ajax request. You'll see more of what's going on.

Cronix's avatar

I think this is what you want. Remove the submit button. You don't need it.

<form id="myForm">
    <div class="button dropdown">
      <select name="languageSelected" required="required" id="languageselector">
        <option value="">Select the language</option>
        @foreach($reviewForm_language as $lang)
         <option value="{{$lang->id}}">{{$lang->name}}</option>
        @endforeach
      </select>
    </div>
  </form>

javascript to submit the form when select is changed

$(function() {
    // when select changes
    $('#languageselector').on('change', function() {

        // create data from form input(s)
        let formData = $('#myForm').serialize();

        // send data to your endpoint
        $.ajax({
            url: '/selected/languageId',
            method: 'post',
            data: formData,
            dataType: 'json', // we expect a json response
            success: function(response) {
                // whatever you want to do here. Let's console.log the response
                console.log(response); // should show your ['success'=> $request->id]
            }
        });
    });
});
public function selectedLangId(Request $request)
{
    // since form input is languageSelected...
    return response()->json(['success'=> $request->languageSelected]);
}

One thing you're missing is your csrf token. You can set that up once and not worry about it again for any more of your ajax requests if you set it up like they show in the docs: https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token

bobmyles's avatar

@CRONIX - Hi @cronix your way of doing it works well... The request hits the controller.. Works as expected!

Quick question, on the view with the form myForm how do I get back the languageSelected passed to controller to reuse on that view?

I mean how do I get this languageSelected from this return response()->json(['success'=> $request->languageSelected]); on the view?

Cronix's avatar

It's already returned to the "view". It's in response that is returned to your success method of the ajax call. I'm dumping it out to console and you should see if if your dev tools are open and view the console tab.

if you console.log(resopnse.success); it would show the actual id of the selected language. From there, I don't know what you want to do with it.

Please or to participate in this conversation.