1

I have a form in Laravel where I use Ajax to dynamically create options in the selects, based on previous filled information. I am very new to Ajax, so maybe I understand the concept wrong.

Below the first select, just based on a "regular" query.

<select id="selectCompany" name="companyId">
  @foreach($companies as $company)
     <option value="{{ $company->id }}">{{ $company->name }}</option>
  @endforeach
</select>

Based on the first selected value, I use Ajax to select options for the next selection field.

$(document).ready(function () {
  $('#step1').on('click', function (fetchLocations) {
    $.ajax({
      type: 'GET',
      url: '/get/info/',
      dataType: 'json',
      data: {
        companyId: $('#selectCompany option:selected').val()
      },
      success: function (response) {
        $('#selectLocations').empty();
        $.each(response.locations, function (key, value) {
          $('#selectLocations').append('<option value=' + key.id + '>' + value.title + '</option>');
        });
      },
      error: function (ts) {
        alert(ts.responseText);
      }
    });
  });

I add the options to the following select

<select id="selectLocations" name="locationId">
</select>

Now I want to submit the form via normal Laravel route, unfortunately the value send from the second select is "Undefined". How can I fix this?

Laravel Request parameters:

Laravel Request parameters

3
  • What kind of structure does the /get/info/ url return in response to the ajax request? Can you add an example? Commented Jun 9 at 19:03
  • @Marleen in JSON format, {"locations":[{"id":5,"title":"Test4"}]} Commented Jun 9 at 19:29
  • Use $('#step1').on('change', This will call the ajax after the value is changed. $('#step1').on('click' calls the ajax before the value is selected for the first dropdown. Commented Jun 10 at 3:27

1 Answer 1

2

The problem is with this line:

$('#selectLocations').append('<option value=' + key.id + '>' + value.title + '</option>');

The short answer is that key.id should be value.id like this:

$('#selectLocations').append('<option value=' + value.id + '>' + value.title + '</option>');

You should be able to see why if you add a console.log inside your $.each to print key and value to console. key will be an int representing the array index, and value will be the object you're returning from /get/info/.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.