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

CookieMonster's avatar

how to pass parameter in ajax for laravel?

I want to submit an ajax request to edit a reply without reloading the page.

So my jquery Ajax would be something like below:

<script>

     $(document).ready(function(){
         $('#ajaxRequest').click(function(e){
            e.preventDefault();
            $.ajaxSetup({
                headers:{
                    'X-CSRF-TOKEN':$("meta[name='csrf-token']").attr('content')
                }
            });

            $.ajax({
                url:"{{url('/replies/'.$reply->id)}}.'/edit'",,
                method:'GET',
                data: {
                    
                }
            });
         });
     });
 

</script>

My route would be:


//Show reply to a thread(via Ajax)
Route::get('/replies/{reply}/edit','RepliesController@edit');

How do I pass my parameter to the url in ajax?

0 likes
10 replies
chaudigv's avatar

Pass data like this

data: {
    name: 'Johnny',
    message: $("#message").val()
},

And then in your controller

use Illuminate\Http\Request;

public function edit(Request $request, $reply) {
    $message = $request->get('message');
}
tykus's avatar

If you name the Route, then you can use the Route helper:

Route::get('/replies/{reply}/edit','RepliesController@edit')->name('replies.edit');

The route helper takes the name of the route, and the model as the second parameter:

$.ajax({
    url:"{{ route('replies.edit', $reply) }}",
    method:'GET',
    data: {}
});

Note, GET requests do not need a CSRF token, so the ajaxSetup is un necessary for this particular request. I don't see how you are handling the response to display the form, or how you are returning a partial view termplate from your controller, so I assume you have this in hand?

CookieMonster's avatar

I am working on it actually.

In ajax url, you can use blade template helper right?

So i can do something like this:

$.ajax({
    url:"{{ route('replies.edit', $reply->id) }}",
    method:'GET',
    data: {}
});

As for the handling the display form, I can to be able to replace my current div tag that shows the reply with a textarea that allows me to edit it. This means, I don't want to use modal(the edit form that pops out after you hit edit) but rather the reply body automatically shifts to a textarea with the current reply and allowing me to write on it and update it. Is it very difficult to tackle?

Update:

It looks something like this:

 $(document).ready(function(){
         $('#ajaxRequest').click(function(e){
            e.preventDefault();

            $.ajax({
                url:"{{route('reply.edit',$reply->id)}}",
                method:'GET',
                data: {
                },
                success:function(response){
                    alert(response);
                    //hide the reply body?
                    //display textarea
                }),
                error:function(error){
                    alert(error);
                }
            });
         });
     });
 

Image for reference:

https://ibb.co/0Vz4zhC

tykus's avatar

In ajax url, you can use blade template helper right?

Assuming this javascript code is located in a Blade Template, and therefore passed through the Blade compiler, yes.

I can to be able to replace my current div tag that shows the reply with a textarea that allows me to edit it

From your controller, you should return a partial as a rendered HTML string rather than a full response; typically something like this (assuming a conventional approach:

return view('replies.edit', compact('reply'))->render();

Then the success callback in your ajax call, you would take that response and put it into the target div, something like this (I don't use jQuery for years so YMMV):

$.ajax({
    url:"{{ route('replies.edit', $reply->id) }}",
    method:'GET',
    data: {},
    success: function (response) {
		$('div#reply-body').hide();
		$('div#edit-form').html(response).show();
    }
});
CookieMonster's avatar

Does passing the named routed in url allows me to use route model binding?

You could see my latest update reply as to how I want the form to show though. Meaning I need to hide edit button along with delete button, then introduce the textarea with the response data and with the say, cancel and update(or savE) button.

I can imagine using a front end framework will ease the job compared with ajax.

tykus's avatar

Does passing the named routed in url allows me to use route model binding?

Yes.

Meaning I need to hide edit button along with delete button, then introduce the textarea with the response data and with the say, cancel and update(or savE) button.

This is all possible with jQuery if you are returning server-render HTML that is swapped into the DOM.

I can imagine using a front end framework will ease the job compared with ajax.

Yes, and no. Laravel Livewire is essentially this pattern of partial DOM changes using server-rendered HTML; you might find that approach easier?

CookieMonster's avatar

Yea I totally forgot about livewire but since I am already tinkering with javascript jquery/ajax, I thought might as well use this approach?

So now my code looks like this overall:

my blade template:

//will hide this if user click on edit
<div id="reply-body" class="card-body">
      {{$reply->body}}
</div>
// will show this if user click on edit
    <div class="card-body">
      <form id="edit-form" action="">
        <div class="form-group mt-2">
          <textarea class="form-control" name="body" id="body" rows="5">Show the fetch reply?</textarea>
        </div>
    <button type="submit">Cancel</button>
        <button type="submit" class="btn btn-dark">Update Reply</button>  
      </form>
    </div>

And then in controller reply:

 public function edit(Reply $reply){
        $reply_body = $reply->body;
        //not sure about the return data
        return view?
    }
    

and in my ajax:

  $(document).ready(function(){
         $('#ajaxRequest').click(function(e){
            e.preventDefault();

            //var reply_id = $('#replyID').val();
            // $.ajaxSetup({
            //     headers:{
            //         'X-CSRF-TOKEN':$("meta[name='csrf-token']").attr('content')
            //     }
            // });

            $.ajax({
                url:"{{route('reply.edit',$reply->id)}}",
                method:'GET',
                data: {
                },
                success:function(response){
                    alert(response);
                    $('#reply-body').hide();
                    $('#edit-form').show();
                }),
                error:function(error){
                    alert(error);
                }
            });
         });
     });
 

Is the logic correct?

How do I show the fetch reply body to the edit form?

Then after that, I'll need to make another ajax to submit the updated reply and show the latest reply and hide the form again?

tykus's avatar

The point of this approach is to return a view partial which you swap into a placeholder div; so there would be a Blade template that is the entire form markup with the Reply body content:

// views/replies/_edit.blade.php

<form id="edit-form" action="{{ route('replies.update', $reply) }}">
    <div class="form-group mt-2">
        <textarea class="form-control" name="body" id="body" rows="5">Show the fetch reply?</textarea>
    </div>
    <button type="submit">Cancel</button>
    <button type="submit" class="btn btn-dark">Update Reply</button>  
</form>

Then in the controller, you would return this as a HTML string:

 public function edit(Reply $reply)
{
    return view('replies._edit', compact('reply'))->render();
}

On the client side, you will target the empty #reply-form div and write the response HTML in there

<div id="reply-body" class="card-body">
      {{$reply->body}}
</div>
<div id="reply-form" class="card-body">
		<!-- the form will be rendered in here -->
</div>

The response from the AJAX request; will be written into the #reply-form div.

$.ajax({
    url: "{{route('reply.edit',$reply->id)}}",
    method: 'GET',
    data: {},
    success: function (response) {
        $('#reply-body').hide();
        $('#reply-form').html(response).show(); // writes the form markup into the div
    }),
    error: function (error) {
        alert(error);
    }
});
1 like
CookieMonster's avatar

okay. I thought instead of writing the form markup into the div, I can directly inject into the blade.template. Will that work too(assuming I do not want to create _edit.blade.php)? test

Please or to participate in this conversation.