No data in axios API request with Laravel Vue.js and FormData()

While working on updating data in Model using API with Laravel and Vue.js, I encountered an issue where FormData() appears to be empty. I checked the formdata using the following code:

for (var value of formdata.values()) {
        console.log(value);
      }

Unfortunately, the output was empty.

Here is the result I obtained:

https://i.sstatic.net/kHFZE.jpg

This snippet shows my update function implemented on a Vue page:

    getFile: function (event) {
      this.image = event.target.files[0];
    },
    updateData: function () {
      let config = {
          header: {
            "Content-Type": "multipart/form-data",
          },
      };
      let formdata = new FormData();
      // Append all necessary information to formdata
      for (var value of formdata.values()) {
        console.log(value);
      }

      axios
        .post(
          "http://localhost:8000/api/edit-pro/" + this.products.id,
          formdata,
          config
        )
        .then(() => {
          //this.$router.push("/control-panel", response);
        });
    },

Below is the controller method responsible for updating the data:

public function updatePro(Request $request, $id)
    {
        $product = Product::find($id);

        // Update product details
        // File handling code...

        try {
            $product->save();
            return ["msg" => "The product was updated successfully"];
        } catch (Exception $error) {
            return [
                "msg" => "The product was not updated successfully",
                "error" => $error,
            ];
        }
    }

The HTML section below uses Vue.js objects to pass to functions:

<form
              id="main-contact-form"
              class="contact-form row"
              name="contact-form"
            >
              <!-- Form inputs omitted for brevity -->
              <div class="form-group col-md-12">
                <input
                  type="button"
                  name="submit"
                  class="btn btn-primary pull-right"
                  value="تعديل"
                  @click="updateData(products.id)"
                />
              </div>
            </form>

If you need more information or have any questions, feel free to ask. Thank you for your assistance!

Answer №1

It appears that there are property products in your possession with the necessary values.

Instead of:

formdata.append("image", this.image);
formdata.append("name", this.name);
formdata.append("price", this.price);
formdata.append("details", this.details);
formdata.append("subject", this.subject);

Try:

formdata.append("image", this.image);
formdata.append("name", this.products.name);
formdata.append("price", this.products.price);
formdata.append("details", this.products.details);
formdata.append("subject", this.products.subject);

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 function Promise.all typically yields an array with nested arrays

Inside my node Router, the following code snippet is implemented: router.get("/single-base/:id", (req, res) => { Base.find({ _id: req.params.id }) .then(bases => { let basefetches = []; for (let base of bases) { ...

What could be causing the kendo autocomplete to display [object Object]?

I have encountered an issue when trying to update my kendo autocomplete using the code below. It displays [object Object] in the UI. <ng-template kendoGridCellTemplate let-dataItem="dataItem" let-rowIndex="rowIndex"> <kendo ...

Inconsistency found in Ajax DataTable data updates

Incorporating a DataTable ajax feature, I pass values to the controller. Here is a simplified version of the code: $(function() { $("#tableDiv").hide(); $("#submitDateFilters").on("click", function() { displayData(); $("#tableDiv").show(); ...

How come my useEffect still contains outdated data?

I have encountered an issue with my useEffect in a React component. Despite having all the necessary dependencies, the state does not update after the useEffect completes. It always displays the previous render. Below is the code snippet of the hook: exp ...

unable to save array using chrome extension storage API

Currently, I am in the process of developing a Chrome extension and utilizing the Storage API. The information regarding this can be found here. To my understanding, it is feasible to store JS objects and arrays through this method. Below is an excerpt of ...

Showing various pictures using numerous buttons in JavaScript

Looking for some assistance with my JavaScript project. I am new to coding and trying to create a program that displays different images when buttons are clicked. Can anyone lend a hand? Here's the code I have so far: <html> <body> < ...

Embedding PHP code within inline styles

Is it possible to incorporate a variable inside my progress bar? I want the progress to change based on the status of each project ($projek), but inserting the variable directly into the style attribute doesn't seem to be working. Here's the code ...

Ways to update the DOM following modifications to a data attribute

I'm currently working on a small CMS system that handles translations for static pages in multiple languages. The system refreshes and loads translations dynamically, but I've encountered some bugs that are proving difficult to resolve. One issue ...

Is it possible to use Markdown in JavaScript without needing to enclose it in <p>

Is there a way to convert markdown text to HTML using JS libraries like markdown-js or marked without wrapping it in paragraph tags? For instance, I want to change this *italic* text to this <i>italic</i> text without including it within <p ...

Utilizing LocalForage's asynchronous `getItem()` method involves awaiting the retrieval of two variables before completing the loading process

I'm still getting the hang of working with asynchronous Javascript calls and handling promises. It's a shift from my usual mindset of Do This, Wait for This. Currently, I'm utilizing localforage on my website and need to retrieve data from ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Troubleshooting problem with BxSlider and collapsible elements in Bootstrap

I'm facing a challenge trying to integrate a bootstrap collapsible element into a bxslider slide without success. Does anyone have any suggestions on how to resolve this issue? Feel free to check out my sample code on the following link: ...

Tips for saving 20000 table rows in the local storage of a Web Browser

I have been tasked with storing all records in the browser's local storage and utilizing them for searching, sorting data, and displaying results on the viewport. My preference is to use WebSql; however, not all browsers support it. I am seeking guida ...

Adding products to an owl-carousel in an HTML document using JavaScript

When I try to add my products to an owl-carousel using JavaScript, the display is not correct. My HTML code looks like this: <div class="container mt-5 mb-5" data-aos-anchor-placement="top-center"> <div class="owl-carouse ...

Inserting a new row into a particular table

I am working on a project where I have a table that displays different exercises. My goal is to allow users to add a new row for each exercise individually. Currently, the snippet below shows how I have implemented this: <!DOC ...

Prevent the modification of the modal attribute in Laravel based on the user's role

In the system I am developing, users have different roles with specific permissions. Certain fields are restricted and can only be updated by users with a particular permission. For instance, a user may have an attribute such as "email" that requires the ...

Automating the process of submitting a checkbox

Displayed below is a mix of HTML and JavaScript: <form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>"> <input type="hidden" name="user" value="<?php echo $employee->id; ?&g ...

JavaScript failing to trigger autoClose functionality in Bootstrap dropdown

I tried implementing this code to toggle a bootstrap 5 dropdown, but the autoClose feature didn't work as expected. const dropdown = new bootstrap.Dropdown(document.querySelector('.dropdown-menu'), { autoClose: true }) dropdown.toggle() ...

When using Next JS with StoryBook, an error may occur if styles are written in a module.scss file

Every time I try to add some styles to my ButtonWidget.scss file, I encounter an error in the console when running the command yarn storybook Error Code: ERROR in ./src/components/ButtonWidget/ButtonWidget.module.scss 1:0 Module parse failed: Unexpected ...

Arranging a group of objects in Angular2

I am facing challenges with organizing an array of objects in Angular2. The structure of the object is as follows: [ { "name": "t10", "ts": 1476778297100, "value": "32.339264", "xid": "DP_049908" }, { "name": "t17", "ts": 14 ...