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

ajsmith_codes's avatar

Keep old value of select - ajax based edit form.

This is similar to another question I've asked, but there's a new twist to it.

Choose the country, it loads the states. Then choose the state and it loads the cities. Ajax based.

This is in an Edit form, so I also need to load the current value, if one exists, from the Customer's record.

So far so good. My problem is this:

If validation fails, I can only seem to retrieve the key of the select, not the value.

Here is the current form code:

{{ $customer->address ? $customer->address->country : '' }} @foreach ($countries as $country => $value) {{ $value }} @endforeach

Countries are pre-loaded in a variable from the Controller.

Here is the javascript code that runs when the select is changed:

$('select[name="country"]').on('change', function () {

    var countryId = $(this).val();

    if (countryId) {
        $.ajax({
            url: '/api/states/get/' + countryId,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {

                $('select[name="state"]').empty();

                $('select[name="state"]').append('<option value="Choose">Select State</option>');

                $.each(data, function (key, value) {

                    $('select[name="state"]').append('<option value="' + key + '">' + value + '</option>');

                });
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            }
        });
    } else {
        $('select[name="state"]').empty();
    }

});

Any idea how to put the old value in? If I use old('country') I get the key, not the value.

0 likes
2 replies
jlrdw's avatar

It's a lot more work when using ajax: https://stackoverflow.com/questions/61030806/keep-old-select-value-while-validation-failed-in-ajax-in-laravel

I generally show errors in a div:


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

                    if (status === 403 || status === 500) {
                        $('#msg').text("Not Auth");
                    }
                }

You would probably be better off YES do the put or post with ajax, but have the select regular form, not ajax - just my opinion. That way old data is easier.

I did a gist for checkbox array, it's similar for select:

https://gist.github.com/jimgwhit/3c1026871ca4246d6ae9f71012ba8e4d

I plan on doing one for select when I get time.

Here is the whole put method:

    $(function () {
        $("#postjqzz").click(function (event)
        {
            event.preventDefault();
            alert("here");
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');
            $post._token = document.getElementsByName("_token")[0].value
            $post._method = document.getElementsByName("_method")[0].value
            alert($post.species);
            $.ajax({
                url: '<?= DIR . "pet/petupdate" ?>',
                type: 'PUT',
                data: $post,
                cache: false,
                success: function (data) {
                    var message = "data updated";
                    alertWithoutNotice(message);
                    $('#msg').append('<div>' + data.success + '</div>');

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

                    if (status === 403 || status === 500) {
                        $('#msg').text("Not Auth");
                    }
                }
            });
        });




        function alertWithoutNotice(message) {
            setTimeout(function () {
                alert(message);
            }, 1000);
        }

    });

ajsmith_codes's avatar

Sorry, I was a bit unclear on the submit. I don't use ajax to submit. I only use it to get the states and cities.

I'll check out the link. Thanks!

Please or to participate in this conversation.