ryan_160289's avatar

Old input not working when using AJAX drop down dependent list

When I using AJAX to populate dependent drop down list and some field in form get error on validate, Laravel return back to page but value at my dependent drop down list it can't to passing old value. This is my code:

This parent dropdown to populate child dropdown, this old input working fine:

 <select class="form-control @error('country') is-invalid @enderror" name="country" id="country" value="{{ old('country') }}">
<option class="text-muted" value="" disabled selected>Chose Country</option>
  @foreach($country as $country_name => $country)
<option value="{{ $country_id }}" {{ (old('country') == $country ? "selected":"") }}>{{ $country_name}}</option>
@endforeach
</select>

But in this child dropdown (dependent from country) old input can't work:

 <select class="form-control @error('state') is-invalid @enderror" name="state" id="state" value="{{ old('state') }}">
</select>

How I do to this problem? Thank you.

0 likes
5 replies
jlrdw's avatar

You are using ajax, you have to display the errors:

error: function (data, ajaxOptions, thrownError) {
                    var status = data.status;
                    //alert(status);
                    if (data.status === 422) {
                        $.each(data.responseJSON.errors, function (key, value) {
                            $('#msg').append('<div>' + value + '</div>');
                        });
                    }

I use a div to show errors

I suggest you take some JS ajax tutorials.

ryan_160289's avatar

Thank you, i'm not to show the error because Laravel have do with validate. My concern is why old input is not working to my child drop down list. I have try jquery to set selected value but not working like :

var oldvalue= "{{ old('state') }}";

$("#state select").val(oldvalue);

Thanks.

artcore's avatar

Simply don't redirect back if you're using ajax and all inputs will remain. Use the ajax callback to populate errors and what not from the validation. You may need a preventDefault() on the button submit handler to prevent the page from refreshing.

jlrdw's avatar

That's why I mentioned take some Ajax JavaScript tutorials to get a better understanding. in Ajax you return a response , it's not using session. There is no old data.

Please or to participate in this conversation.