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

mozew's avatar
Level 6

How to call edit method of the resource controller using AJAX in Laravel5.6

In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.

my blade

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <title>{{ config('app.name') }}</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
    <link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
    <h1>{{ config('app.name') }}</h1>
    <form class="dis-none" id="FormAjax">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" />
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="address">Address</label>
                    <textarea class="form-control" rows="3" id="address"></textarea>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="country">Country</label>
                    <input type="text" class="form-control" id="country" />
                </div>
            </div>
        </div>
        <button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
        <button type="button" id="cancel" class="btn btn-danger">Cancel</button>
    </form>
    <div id="ShowAjax" class="row">
        <button type="button" id="AddForm" class="btn btn-success">Add Form</button>
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Address</th>
                <th>Country</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody id="data">
            </tbody>
        </table>
    </div>
</div>

<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $("#AddForm").click(function () {
            $("#FormAjax").fadeIn();
            $("#ShowAjax").hide();
            $('#UpdateForm').text('Save Form');
        });
        $("#SaveAjax").click(function () {
            $("#FormAjax").hide();
            $("#ShowAjax").fadeIn();
        });
        $(document).on('click', '#cancel', function () {
            $('#name').val('');
            $('#country').val('');
            $('#address').val('');
        });
        $(document).on('click', '#edit', function () {
            $("#FormAjax").fadeIn();
            $("#ShowAjax").hide();
            name = $(this).parent().parent().find('#ename').text();
            address = $(this).parent().parent().find('#eaddress').text();
            country = $(this).parent().parent().find('#ecountry').text();
            $('#name').val(name);
            $('#address').val(address);
            $('#country').val(country);
            $('#SaveAjax').text('Edit');
            $('#SaveAjax').prop('id', 'UpdateForm');
            $('#UpdateForm').attr('data-id', $(this).data('id'));
        });
        $(document).on('click', '#UpdateForm', function () {
            name = $('#name').val();
            country = $('#country').val();
            address = $('#address').val();
            url = "peoples";
            id = $(this).data('id');
            editUrl = url + '/' + id + '/edit';
            $.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
                console.log('success');
            });
        });
    });
</script>
</body>
</html>

route/web.php

Route::resource('peoples', 'PeopleController');

PeopleController.php

public function edit(People $people)
    {
        if($request->ajax()) {
            $request->validate([
                'name' => 'required',
                'address' => 'required',
                'country' => 'required',
            ]);
            
            $people = People::find($request->id);
            $people->name = $request->name;
            $people->address = $request->address;
            $people->country = $request->country;
            $people->save();
            
            return response()->json();
        }
    }

When I try type in browser http://localhost:8000/peoples I see this error.

Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials Laravel\Ajax\resources\views\peoples.blade.php)

0 likes
15 replies
36864's avatar
$(document).on('click', '#UpdateForm', function () {
           name = $('#name').val();
           country = $('#country').val();
           address = $('#address').val();
           url = "peoples";
           id = $(this).data('id');
           editUrl = url + '/' + id + '/edit';
           $.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
               console.log('success');
           });
       });

{{route('editUrl')}} is compiled on your server, not on the client. The route() helper fetches a route by a name that has been defined, but you haven't defined any route named 'editUrl'.

Since you're already manually building the url, just use that instead of the route helper:

$(document).on('click', '#UpdateForm', function () {
            name = $('#name').val();
            country = $('#country').val();
            address = $('#address').val();
            url = "peoples";
            id = $(this).data('id');
            editUrl = url + '/' + id + '/edit';
            $.get( editUrl, {name:name, country:country, address:address, id:id}, function (data) {
                console.log('success');
            });
        });
Cronix's avatar

2 problems

  1. route('editUrl') should be route('peoples.update') if you are using a standard resourceful controller generated by artisan. This will also only work if you're in a blade.php file, not a js file
  2. Updating requires a PUT request (or PATCH). You're using GET for your ajax request.

You can see the default route names for resourceful controllers here: https://laravel.com/docs/5.6/controllers#resource-controllers

1 like
mushti's avatar

As @Cronix suggested use route('peoples.update') then use $.ajax() method with type: 'PUT'

$(document).on('click', '#UpdateForm', function () {
    name = $('#name').val();
    country = $('#country').val();
    address = $('#address').val();
    url = "/peoples";
    id = $(this).data('id');
    editUrl = url + '/' + id + '/edit';
    $.ajax({
        url: {{ route('peoples.update') }},
        type: 'PUT',
        data: { name: name, country: country, address: address, id: id },
        success: function(result) {
            console.log('success');
        }
    });
});
1 like
Cronix's avatar

This should work too. No point in all of that extra code to get the form inputs and set them individually in the data portion of the request, as jQuery has a nice method to do that for you.

$(document).on('click', '#UpdateForm', function () {
    
    $.ajax({
        url: {{ route('peoples.update') }},
        type: 'PUT',
        data: $('#FormAjax').serialize(),
        success: function(result) {
            console.log('success');
        },
        error: function(data) {
            // you'd want to show your validation errors if there are any, as well
            console.log(data);
        }
    });
});
mozew's avatar
mozew
OP
Best Answer
Level 6

I tried this

$(document).on('click', '#UpdateForm', function () {
            name = $('#name').val();
            country = $('#country').val();
            address = $('#address').val();
            url = "peoples";
            id = $(this).data('id');
            editUrl = url + '/' + id + '/edit';
            $.get( editUrl, {name:name, country:country, address:address, id:id}, function (data) {
                console.log('success');
            });
        });

But this is not edit . this is added. I see this error in console.

GET http://localhost:8000/peoples/1/edit?name=John%20Sina&country=USA&address=End%20of%20Sina&id=1 500 (Internal Server Error) send @ app.js:1 ajax @ app.js:1 _.(anonymous function) @ app.js:1 (anonymous) @ peoples:152 dispatch @ app.js:1 g.handle @ app.js:1

I just wanna edit the form

2 likes
mozew's avatar
Level 6

I tried point #2. I see this error mesage.

Missing required parameters for [Route: peoples.update] [URI: peoples/{people}]. (View: C:\xampp\htdocs\Tutorials Laravel\Ajax\resources\views\peoples.blade.php)

yansusanto's avatar

@irankhosravi

You got your AJAX function all wrong. Please refer to @Cronix 's method and you are good to go.

$(document).on('click', '#UpdateForm', function () {
    
    $.ajax({ // <------ please pay attention to this
        url: {{ route('peoples.update') }}, 
        type: 'PUT',
        data: $('#FormAjax').serialize(),
        success: function(result) {
            console.log('success'); 
        },
        error: function(data) {
            // you'd want to show your validation errors if there are any, as well
            console.log(data);
        }
    });
});
mozew's avatar
Level 6

@yansusanto

I see this error message.

Missing required parameters for [Route: peoples.update] [URI: peoples/{people}]. (View: C:\xampp\htdocs\Tutorials Laravel\Ajax\resources\views\peoples.blade

Cronix's avatar

Ah, yeah, you need to pass the id that you want to edit to the route, but I don't see anywhere where you're posting it...

url: {{ route('peoples.update', $idToUpdateGoesHere) }}, 
mozew's avatar
Level 6

@Cronix

I tried your point for example

           $(document).on('click', '#UpdateForm', function () {
            $.ajax({
                name = $('#name').val();
                country = $('#country').val();
                address = $('#address').val();
                url = "peoples";
                id = $(this).data('id');

                url: {{ route('peoples.update', id) }},
                type: 'PUT',
                data: $('#FormAjax').serialize(),
                success: function(result) {
                    console.log('success');
                },
                error: function(data) {
                    // you'd want to show your validation errors if there are any, as well
                    console.log(data);
                }
            });
        });

Too I see this error.

Use of undefined constant id - assumed 'id' (View: C:\xampp\htdocs\Tutorials Laravel\Ajax\resources\views\peoples.blade.php)

Cronix's avatar

Yes, because you're trying to use a javascript variable inside the blade {{ }} tags, which is php. You can't mix them like that - they are totally separate languages.

url: {{ route('peoples.update', $YourObjectYoureEditing->id) }}, 

If you're editing something that exists, I assume you are retrieving the model that you're editing and passing it to the view with your form. You don't show any of that controller code where you are displaying the form view, so I don't know exactly what to show you.

Cronix's avatar

If you're editing something that exists, I assume you are retrieving the model that you're editing and passing it to the view with your form. You don't show any of that controller code where you are displaying the form view, so I don't know exactly what to show you.

akshatsoni64's avatar

Can u help me @cronix , i tried the way u tols, but it redirects to show method instead of update method! i changes the method to put, after that also no luck!

Please or to participate in this conversation.