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

coder_uzb's avatar

save old data after refresh page with ajax

HI guys. I have select box and I use on change method with ajax. This is my select box

<select class="select js-delivery" name="delivery_id">
                                    <option selected disabled>Choose delivery type</option>
                                    @foreach($deliveries as $delivery)
                                        <option value="{{$delivery->id}}">{{ $delivery->title }}</option>
                                    @endforeach
                                </select>

and here my ajax.

$(document).on('change', '.js-delivery', function(e){
            delivery.show();
            var delivery_id = $(this).val();            
                $.ajax({
                    type:'GET',
                    url:'get/delivery', 
                    data: {'id':delivery_id},
                    success:function(data){

                    var type = $('.delivery-type');
           type.html(data.title);   
                    },
                    error:function(data){
                        console.log('error');
                    }      
                });
        });

After this I submitted form and page refreshed. But when I was laravel errors I am losing select box value. How can I save old data?

0 likes
2 replies
Snapey's avatar

You cannot use ajax posting and also refresh the page - its pointless. Do one or the other.

deansatch's avatar

It looks like he is trying to submit the form as normal but is using ajax during filling out the form to pull in a title to display elsewhere on the page which is fine...however, it looks like you already have the titles in your dropdown so why not just scrap the whole ajax call and do:

$(document).on('change', '.js-delivery', function(e){
                delivery.show();
        $('.delivery-type').html($(this).text());    
        });

Then, if you want your form to remember the selection on error, try using the form builder and it will take care of that for you. You can always run the delivery.show() etc... on doc ready too...if errors are set. Something along these lines:

@if($errors->any())
function populateDelivery(select){
    delivery.show(); //you'll have to set var delivery to whatever it is
    $('.delivery-type').html(select.text()); 
}    
    
$( document ).ready(function() {
    populateDelivery($('.js-delivery').find(":selected"));  
});
$(document).on('change', '.js-delivery', function(e){
    populateDelivery($(this).find(":selected"));  
});  
@endif 

Please or to participate in this conversation.