How to keep old values with ajax in laravel?

Member

by larissa , in category: PHP Frameworks , 4 months ago

How to keep old values with ajax in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a month ago

@larissa 

To keep old values when using AJAX in Laravel, you can use the old() helper function provided by Laravel. This function allows you to retrieve the old input values from the previous request.


Here's an example of how you can use the old() function in your blade file when using AJAX:

  1. In your blade file, add the following code to display old input values:
1
<input type="text" name="name" value="{{ old('name') }}" id="name">


  1. In your AJAX request, you can send the old input values along with the request by including them in the data object:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$.ajax({
    type: "POST",
    url: "your-url",
    data: {
        name: $('#name').val(),
        _token: $('meta[name="csrf-token"]').attr('content'),
        // Include other old input values here
    },
    success: function(response) {
        // Handle response
    },
    error: function(error) {
        // Handle error
    }
});


By using the old() function in your blade file and including the old input values in your AJAX request, you can ensure that the old values are retained and displayed even when using AJAX in Laravel.