Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $request when it comes as an array from AJAX. Usually, I can do something like $request->input('name'), but in this case, I need to access values like

$request->input('firstGrant.issue_date')
due to the format of my data. Can someone please point me in the right direction?

This is what I have tried:

submitCompany() {
 axios.post('/onboarding', {
    name: this.step1.name,
    type: this.step1.type,
    shares_amount: this.step2.shares_amount,
    par_value: this.step2.par_value,
    firstGrant: {
        issue_date: this.step3.firstGrant.issue_date,
        certificate: this.step3.firstGrant.certificate,
        share_price: this.step3.firstGrant.share_price,
        shares_amount: this.step3.firstGrant.shares_amount
    }

})
.then(function (response) {
    console.log(response);
    alert('Information saved!');
})
.catch(function (error) {
    console.log(error);
    alert('Wrong!');
});
}

This is how I've implemented it in my Controller:

public function store(Request $request)
{
    $userId = Auth::user()->id;
    $issueDate = $request->input('firstGrant.issue_date'); //Is there a better way to do this?
    $certificate = $request->input('firstGrant.certificate');//Is there a better way to do this? 
    $sharePrice = $request->input('firstGrant.share_price');//Is there a better way to do this?
    $sharesAmount = $request->input('firstGrant.shares_amount');//Is there a better way to do this?

    $equityGrant = EquityGrant::create([
        'user_id' => $userId,
        'share_id' => 91,
        'vesting' => 0,
        'status' => 'active',
        'issue_date' => $issueDate,
        'certificate' => $certificate,
        'share_price' => $sharePrice,
        'shares_amount' => $sharesAmount,
    ]); }

Answer №1

To ensure that Laravel recognizes axios requests as XHR, you may need to set up axios to include a specific header with each request. Once this is done, the $request->input('x.y') statements should function correctly.

Object.assign(axios.defaults.headers, {
    'X-Requested-With': 'XMLHttpRequest',
});

If you are still encountering issues, it's advisable to verify if axios is correctly adding the CSRF-token to the request header by referring to Laravel's documentation on CSRF protection.

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

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

The VueJS Store concept featuring data access with get and set functions

I run a small boutique using the state pattern in VueJS (not VUEX). Here's how it looks: export default { get selectedPartner() { return localStorage.getItem('selectedPartner'); }, set selectedPartner(item) { ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

Is there a specific jest matcher available for comparing Array<Objects>?

I'm currently testing the equality of two arrays of objects and have found that the toEqual matcher in Jest only works for arrays of strings. Is there another matcher available in Jest that can handle this condition? Please refrain from marking this a ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

The passport.use method is failing to invoke in Node.js when utilizing the passport-local strategy

Upon calling the login and submitting the form, it seems that the use.authenticate() method is not being executed and no error messages are displayed. Server.js code snippet: const passport=require('passport'); const Strategy=require('pass ...

The PhantomJs browser is not able to open my application URL

Recently, my scripts in PhantomJS browser have stopped running. Whenever I try to capture screens, all I get are black screens. To troubleshoot this, I manually opened a URL in PhantomJS using the command window and ran the script below to verify if it ope ...

The specified dependency, * core-js/fn/symbol, could not be located

I am in the process of developing a Vue.js application with Vuex and have encountered some errors during the build. I attempted to resolve the issue by installing npm install --save core-js/fn/symbol, but unfortunately, it did not work as expected. https:/ ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

Transforming button properties into a JSON format

I am currently in the process of developing a web application using node.js and mongodb. Within my app, there is a table that dynamically populates data from the database using a loop. I encountered an issue with a delete function that I implemented base ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...