Laravel AJAX Call


Hello friends,
I hope you guys are doing good. Today’s blog will be about Laravel’s most common functionality we are using nowadays and finding trouble to make it work, so here I am to solve your problem with a simple example of an ajax call with a post method to pass the data and get the result.

In this example, we will have a dropdown of note templates. We will select one, and then it will call the ajax and bring us the content of the template, and then we will put that into a text area.

First, let’s check out the content of the blade.php file.

<select class="form-control" name="template" id="template">
    <option value="">Select Template</option>
    <option value="1">School template</option>
    <option value="1">College template</option>
</select>

<div class="form-group">
    <label class="col-sm-3 control-label">Template Body</label>
    <textarea rows="5" id="message" name="message"  class="form-control"></textarea>
</div>

Now let’s check the ajax call. You can create a js file and import that in your blade file or you can write your code in the blade file in the script section.

$(document).on('change', '#template', fumction () {
    var id = $(this).val();
    var APP_URL = ''; // here you need to put your application url
    if(id) {
        $.ajax({
                type: "POST",
                url: APP_URL + "/get-template-body",
                data: {
                    id: id, 
                    _token: $('meta[name="csrf-token"]').attr("content");
                },
                success: function (response) {
                    $("message").val(response.message);
                },
                error: function(){
                    toastr.error("Something went wrong, please try again later.", "Error Message");
                }
        });
    }
});

Now let’s check the code for the controller.

public function view(Request $request) {
    $id = $request->id;
    $template = Templates::where('id', $id)->first();
    return response()->json([
        'status' => true,
        'message' => $template->body;
    ]);
}

And finally, create the route.

Route::post('/get-template-body','YourController@view');

Hope you got some information from this blog. If you have any queries or doubts you can write them down in the comment section and I’ll try to answer them as soon as possible.

Thank you for reading 🙂

Happy coding 🙂

Comments are closed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started