How to Link Laravel 5 with Ajax?

I've implemented this Laravel code in my controller for the detach function.

$input = Input::all();
    $product= Products::findOrFail($input['product_id']);
    $product->tags()->detach($input['tag_id']);
    $product= Products::where('customer_id', Auth::user()->customers_id)->get();

    return view('products.tagsdelete', [
            'products' => $product,
        ]);

The current setup works well and successfully removes the tag relation from the pivot table. However, I'm looking to avoid page reloads when deleting a tag by using Ajax.

While I could implement a selection process for multiple tag deletions on user input, I prefer real-time deletion with Ajax for efficiency.

I've been trying to figure out how to incorporate detachment with Laravel and Ajax, but haven't found much guidance. Although I'm comfortable with JavaScript and jQuery, Ajax is still relatively new to me.

If anyone has any insights or can help me navigate through this, I would greatly appreciate it. Thanks for your time :)

@Wiriya Rungruang

Current Controller Code:

public function detach()
    {
    $input = Input::all();
    $product= Products::findOrFail($input['product_id']);
    $product->tags()->detach($input['tag_id']);
    $product= Products::where('customer_id', Auth::user()->customers_id)->get();
}

My Button:

<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>

JavaScript at the Bottom of the Code:

   <script>
    $(".delete-tag-btn").on('click', function(){
        var url = "{{ route('detach') }}"; // URL for deleteTag function
        url += "product_id=" + $(this).data('product_id');
        url += "&tag_id=" + $(this).data('tag_id');

        // Updated URL: 'http://localhost/deletetag?product_id=2&tag_id=5'
        // Send GET request with URL to server
        $.get(url, function(response){
            alert("success");
        });
    });
</script>

Answer №1

Initial Step: Begin by creating a function in your controller to detach tags from a product and return a status indicating success or failure.

Code snippet for the controller:

function detachTag(){
    $input = Input::all();
    $product= Products::findOrFail($input['product_id']);
    $product->tags()->detach($input['tag_id']);
    $product= Products::where('customer_id', Auth::user()->customers_id)->get();

    return "You can check here if the operation was successful";
}

Next Step: Develop a JavaScript function that triggers when the delete button is clicked, sending a request with parameters to the previously created function. Update the HTML page accordingly by either re-rendering or removing the tag.

Code snippet for the JavaScript file:

$(".delete-tag-btn").on('click', function(){
    var url = "localhost/deletetag?"; // URL for the deleteTag function
    url += "product_id=" + $(this).data('product_id');
    url += "&tag_id=" + $(this).data('tag_id');

    // The updated URL will look like this: 'http://localhost/deletetag?product_id=2&tag_id=5'
    // Send a GET request with the URL to the server
    $.get(url, function(response){
        // Handle the response as needed
    });
});

By clicking on .delete-tag-btn, a request will be made to detach the tag associated with the product.

Answer №2

To start off, you can create a basic ajax call to send data and receive html for replacing the existing content.

Let's get started!

The first step involves writing the ajax code and triggering it when a form is submitted or a button is clicked (according to your implementation).

Here is a simple example of an ajax request. Make sure to customize it with your specific data:

var BASEURL = window.location.origin + "/your_domain_name/";
    $.ajax({
        url: BASEURL + "your_route",
        type: "POST/GET", // choose one
        data: {
            // Your data goes here (object)
        },
        beforeSend: function () {

        },
        success: function (response) {
            console.log(response); // the returned html
        },
        complete: function (response) {

        }
    });

Once the call is made with your data, it will reach the controller specified in the route you provided, where normal processing will occur. The response will only contain html, which you can utilize as needed.

An important consideration to keep in mind is that if you plan on replacing part of the page with new html instead of refreshing the whole page, ensure that your controller returns only the relevant portion of the view, such as a single row. Divide your view into smaller sub-views, and consider using Php @include(//path) (blade) for this purpose. This approach has proven effective in my experience. :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Choosing HTML Elements for Audio Playback in HTML5: A Guide to Selecting Elements Without Using Div IDs

When creating an HTML5 player, I am transitioning "from using divs with id's" to "simple HTML elements". Former Scenario (functional) <audio src="track1.mp3" id="audio"></audio> <controls> <play id="play" style="display:none ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

Schema design for a real-time messaging platform featuring chat rooms

Currently, I'm working on a university project that involves creating a dynamic live chat website featuring rooms, user registration, and more. I have most of the system planned out except for one crucial aspect - the rooms. In this setup, a room is ...

Vue.js combined with Video.js (MPEG-DASH) is throwing an error: (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)

I am facing an issue with Video.js when using it as a component in vue.js. I receive a .mpd link from a server and I want to display the video from that link. Following the example in the documentation of Video.js and Vue integration. Every time I call th ...

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...

Error message: Node: TypeError - Attempted to access the 'sort' property of an undefined variable while using findOneAndUpdate() within a find() operation

My code snippet is shown below: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/school', function(err, db) { if (err) throw err; db.collection('students').find().toArray( ...

Switching between React components based on a click event

I want to display a component in another component when it is clicked, similar to this scenario: The DevStatus component consists of two Bootstrap radio buttons. Meanwhile, the IssuesList component includes a Bootstrap list. You can view the code on Code ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

What is the process for uploading a single file and an array of files with varying names using multer?

I am having trouble figuring out how to upload a main image and side images from 2 different file inputs using multer. It seems that multer only accepts one upload per route. How can I work around this issue? I keep getting an unexpected field error when a ...

What is the best way to create a jQuery object that encapsulates a snapshot of a DOM element?

Recently, I discovered that a JQuery object retains a reference to a DOM object. As the HTML is modified, the context of the JQuery object also changes. However, my concern now is how to log these changes without altering the history records of the JQuer ...

Having trouble with a jQuery.validationEngine reference error?

Despite everything being correctly referenced, I am facing difficulties in getting it to function properly. It's strange because it worked once, but the validation message took 10 seconds to appear. After that, without making any changes, I tried agai ...

What is the best way to invoke a function from one controller in angularjs to another controller?

I am trying to implement a solution where I need to call the Listing function of testController from userController. I have placed a marker (//) in the code snippet below to indicate where I want to make this function call. This implementation is being d ...

How can I beautify the request object in Node.JS?

How can I improve the readability of a request object in Node.js? The standard console.log output doesn't provide enough information. ...

Determining the size of the axis in correlation to a set constant length

Basic Concept I am currently developing a small tool designed to assist with geometric calculations for print-related items. Project Overview In this tool, users are asked to input the width and height of a box, represented visually as a CSS-based box, ...

Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example: User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar. The desired output would be: [4, 3, 1] This filter works ...

The server nodejs is unable to recognize the dotenv file

This is my very first project with the MERN stack and I'm currently working on pushing it to GitHub. Since I am using Mongoose, I needed to protect the login credentials for my account. After some research, I discovered the solution of using a .env fi ...