The request to remove the product from the server at URL http://localhost:8000/product/[object%20Object] encountered an internal server

I'm having trouble setting up the AJAX delete method. I keep getting a 500 internal server error and despite following tutorials, I remain frustrated. Can someone please help me correct my code?

This is using Laravel 5.8 and jQuery 3.3.

<section class="section">
  <div class="section-header">
    <h1>Our Products</h1>
    <div class="section-header-button">
      <button id="createProduct" class="btn btn-primary">Add New</button>
    </div>
  </div>
  <div class="section-body">
    <div class="row mt-4">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <h4>All Items</h4>
          </div>
          <div class="card-body">
            <div class="clearfix mb-3"></div>
            <div class="table-responsive">
              <table id="itemList" class="table table-striped">
                <thead>
                  <tr>
                    <th>Product Code</th>
                    <th>Product Name</th>
                    <th>Categories</th>
                    <th>Price</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody id="dataTable">
                  @include('product.table')
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


<!-- Modal  -->
<div class="modal fade" id="tambahProductModalLong" tabindex="-1" role="dialog" aria-labelledby="tambahProductModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="tambahProductModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="addProductForm">
        @csrf
        <input type="hidden" name="id" id="id">
        <input type="hidden" name="product_code" id="productCode">
        <div class="modal-body">
          <div class="form-group">
            <div class="section-title">Product Name</div>
            <input required id="name" type="text" name="name" class="form-control">
          </div>
          <div class="form-group">
            <div class="section-title">Categories</div>
            <select name="categories" class="form-control select2">
              @foreach($categories as $c)
              <option value="{{$c->id}}">{{$c->name}}</option>
              @endforeach
            </select>
          </div>
          <div class="form-group">
            <div class="section-title">Price</div>
            <div class="input-group">
              <div class="input-group-prepend">
                <div class="input-group-text">
                  IDR
                </div>
              </div>
              <input required id="price" type="number" name="price" class="form-control currency">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" id="saveButton" class="btn btn-primary"></button>
        </div>
      </form>
    </div>
  </div>
</div>


@foreach($products as $p)
<tr>
    <td>{{$p->code}}</td>
    <td>{{$p->name}}</td>
    <td>{{$cat = App\Category::where('id', $p->categories_id)->first()->name}}</td>
    <td>IDR {{number_format($p->price)}}</td>
    <td>
        <a id="editProduct" data-id="{{$p->id}}" href="#" class="btn btn-icon edit btn-sm btn-primary">
            <i class="far fa-edit"></i>
        </a>
        <a id="deleteProduct" data-id="{{$p->id}}" href="#" class="btn btn-icon delete btn-sm btn-danger">
            <i class="far fa-trash-alt"></i>
        </a>
    </td>
</tr>
@endforeach

Here is my AJAX method:


function load() {
  $.ajax({
    url: "{{route('product.load')}}",
    success: function(response) {
      $('#dataTable').html(response);
    }
  });
}

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

 //delete
$('.delete').click(function(e) {
  e.preventDefault();
  // console.log(1);
  var id = $(this).data(id);
  // console.log(id);
  confirm("Are you sure want to delete?");

  $.ajax({
    type: "DELETE",
    data: {
      "id": id,
      "_token": "{{csrf_token()}}"
    },
    url: "/product/" + id,
    success: function(data) {
      if (data.status == "sukses") {
        alert("data berhasil dihapus");
        load();
      } else {
        alert("data gagal dihapus");
      }
    }
  });
});

Routes:

Route::delete('/{id}', ['as' => 'destroy', 'uses' => 'ProductContntroller@destroy']);
public function destroy($id)
{
    Product::destroy($id);
    $response['status'] = "sukses";

    return Response::json($response);
}

I am encountering an error in the console that looks like this:

localhost::8000/product/[Object%20object] 

Answer №1

Currently, the id is showing as undefined.

var id = $(this).data(id);

Resolution: To rectify this issue, consider utilizing the following code snippet:

var id = $(this).data("id");

If you keep the original code where id is not defined, you will encounter the following result:

var id = $(this).data(undefined);

In addition, if there is no attribute like data- on your element, the statement $(element).data(dataVar) will return an object, causing your DELETE request to be serialized as [object Object].

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

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

Valid ways to ensure that a CSS image expands outside the boundaries of the containing div

I have inserted an image using the following CSS code: .imgtemp { float:right; top:0px; left:0px; overflow:visible; width:100%; } Although I have added the div tag to display it on the page, ...

Steps to Utilize Google Apps Script from a Website

I've been on a mission to find the solution to my problem. I have a basic web page with HTML/CSS/JS. What I want is for users to visit the page and immediately have it call up a Google script I created, which will pull information from a spreadsheet a ...

Accessing WebService Remotely Using Ajax in ASP.NET

CLIENT - AJAX $.ajax({ type: "POST", url: 'http://www.website.com/Service.asmx/Method', data: "{ 'username': 'testuser', 'password': '123456' }", contentType: "applicati ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

Issue with dropdown element not triggering JavaScript onchange event

I am in the process of developing an application that involves searching a database and enabling users to compare the results. To achieve this, I require multiple dependent drop-down menus. While I have some understanding of HTML and PHP, my coding experti ...

When utilizing jQuery to retrieve the height of position:absolute elements, the script is being executed twice, resulting in inaccurate values being returned on

The issue I'm encountering with detecting the height of absolutely positioned content is demonstrated in this JSFiddle. I am working on creating a tabbed panel where users can select a room type and then a sub-type. The sub-types (ul.sub-types) are s ...

Unable to display ChartJs within the same DIV on the webpage

I'm struggling to display the Pie Chart from ChartJs in the correct DIV when I click from the left DIV. Running the chart directly works fine, but I want them both on the same page in separate DIVs. I have separate HTML files for each link and they wo ...

Exporting Python Pandas Data Frame to an HTML file

I'm attempting to save a Python Pandas Data Frame as an HTML page. I also want to ensure that the table can be filtered by the value of any column when saved as an HTML table. Do you have any suggestions on how to accomplish this? Ultimately, I want t ...

Linking Several Users (Speakers) to an Event in Laravel 5.6

My goal is to link a list of users to events by sending an array of user IDs. In Laravel, I have the following table structure: Events Table Schema::create('events', function (Blueprint $table) { $table->increments('id') ...

The interval continues even when the mouse is no longer hovering

I'm having an issue with the interval "myInterval" continuing even after I move the mouse out of the triggering element. Why is it not stopping as expected? $(".postimagepic").mouseenter(function () { var link = $("#blurpost").attr("src").split(" ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Displaying the second div once the first div has loaded, then concealing the first div

Current Approach: There are two divs occupying the same space, with div1 set to display:block and div2 set to display:none When a tab is clicked, jQuery hides one div over a period of 2000ms and reveals the other div. Challenge: The goal is for the ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

The ajax form is submitting without any issues, but why isn't the success function working?

I am having an issue with a basic form that uses jQuery and AJAX to submit data. The form submission itself works without any problems, but for some reason, the success message is not being displayed - only the error message shows up. Can anyone please h ...

Using Jquery to make a Json request and incorporating a callback function to populate an

I have successfully implemented a cascading drop down feature in my form. However, I am facing issues with the callback function not functioning properly after submitting the form. I am unsure what is causing this problem. Despite making suggested changes ...

PHP Ajax Image Uploading and Storage

Is there a way to effortlessly upload an image and save it in the uploads folder without any page refresh? Not only that, but can we also have the uploaded image displayed on the screen within a designated div section? Unfortunately, I seem to encounter a ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Is it feasible to dynamically insert and delete elements in React?

I'm currently in the process of rebuilding a project, specifically a drag and drop website builder, using React after it was originally built with a heavy reliance on jQuery. My main challenge lies in being able to dynamically add and remove elements ...