Vue form not sending data in request - php

I have a form in one component, and I am trying to send data on submit with Ajax request:
<form>
<div class="control">
<input class="input is-large" type="email" v-model="email" required>
<label>E-post</label>
</div>
<div class="control">
<input class="input is-large" type="password" v-model="password" required>
<label>Passord</label>
</div>
<div #click="save" type="submit" class="button hero-button is-medium is-primary">
Logg in
</div>
</form>
This is the method for post request, I am using axios library for Ajax requests:
methods: {
save() {
const form = new FormData();
form.append('email', this.email);
form.append('password', this.password);
this.$backend.post('/user/login', form, {
}).then(() => {
console.log('success');
}, (err) => {
console.log(err);
});
}
}
But, when I check on the backend side, built with laravel, I get an empty request:
{"request":[]}
This is the function in the controller on the backend side:
public function login(Request $request)
{
//testing $request object
return ['request' => $request->all()];
$authenticatedUser = $this->authenticate($request->email, $request->password);
if (!$authenticatedUser) {
$remoteAuthenticated = $this->checkWplUser($request->email, $request->password);
if (!$remoteAuthenticated) {
return $this->response->errorUnauthorized();
}
}
return $this->issueToken($request->email, $request->password);
//return $this->returnUserResponse();
}
This is how the request header looks like:
How can I fix this?

Related

Submitting a form via Fetch API in Laravel

I've been trying to submit the form via a Fetch API, but having no luck so far. I can submit the form without one, but for this exercise it has to be with Fetch.
Form
<form action="{{ url('/process')}}" method="POST">
#csrf
<div class="form-container">
<div class="form-item">
<label for="name">Full Name<span class="required">*</span></label>
<input type="text" name="name" id="name" placeholder="Enter your name" />
</div>
<div class="form-item">
<label for="email">Email<span class="required">*</span></label>
<input type="email" name="email" id="email" placeholder="Enter your email address" required />
</div>
</div>
<div class="form-container">
<button type="submit">Submit</button>
</div>
</form>
^This submits successfully as is, but again I need to use Fetch.
Fetch API:
form.addEventListener("submit", (e) => {
e.preventDefault();
const csrfToken = document.querySelector("input[name='_token']").value;
fetch("success.blade.php", {
method: "post",
body: JSON.stringify(process),
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken,
},
})
.then((response) => {
console.log(response);
return response.text();
})
.then((text) => {
return console.log(text);
})
.catch((error) => console.error(error));
}
Routes
Route::get('/', [ContactController::class, 'create']);
Route::get('/all', [ContactController::class, 'getAll']);
Route::post('/process', [ContactController::class, 'store']);
ContactController.php
public function store(Request $request)
{
$contact = Contact::create($request->input());
$message = 'Thank you for your message! We will review your submission and respond to you in 24-48 hours.';
if ($request->ajax()) {
return response()->json(compact('message'));
}
return view('success');
}
success.blade.php is a file I created to display that thank you message, but something tells me I don't need it if I'm using this function store right.
If I remove action="{{ URL('/process') }} , and just use the Fetch API, then I get this error:
The POST method is not supported for this route. Supported methods: GET, HEAD.
you should not send fetch request to the blade
you must send request to controller
change url of fetch with controller

window.location.href will not redirect at all

When I log in using my Ajax login form, it shows an error instead of redirecting to the dashboard with:
window.location.href = "https://my.distincttrack.com/admin/";
If I refresh the page it will redirect me to the dashboard because of the auth guard in the laravel middleware. But the code I posted above is not at all redirecting me to that page when the response is a success.
I tried changing it to window.location but that did not help. I took out the double quotes and that did not work so I put them back. I tried turning off ajax and seeing what a normal form HTTP submit would respond and it echoed success as it should have.
My Jquery Ajax Code:
return {
init: function () {
l(), $("#m_login_signin_submit").click(function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var a = $(this), l = $(this).closest("form");
l.validate({
rules: {
email: {required: !0, email: !0},
password: {required: !0}
}
}), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0), l.ajaxSubmit({
url: "",
method: "post",
data: {
email:jQuery('#email').val(),
password:jQuery('#password').val()
},
success: function (response) {
if(response==="success") {
window.location.href="https://my.distincttrack.com/admin/";
} else {
setTimeout(function () {
a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1), i(l, "danger", "Incorrect username or password. Please try again.")
}, 2e3);
}
}
}))
}),
My controller where the user is logged and a response is made:
public function store(Request $request)
{
if (Auth::guard('system')->attempt(['email' => $request['email'], 'password' => $request['password'], 'status' => 1], $request['remember'])) {
return 'success';
}
return 'failed';
}
My HTML View in the blade:
<form class="m-login__form m-form" action="" method="post">
#csrf
<div class="form-group m-form__group">
<input class="form-control m-input" type="email" placeholder="Email" name="email" autocomplete="off" required>
</div>
<div class="form-group m-form__group">
<input class="form-control m-input m-login__form-input--last" type="password" placeholder="Password" name="password" required>
</div>
<div class="row m-login__form-sub">
<div class="col m--align-left m-login__form-left">
<label class="m-checkbox m-checkbox--light">
<input type="checkbox" name="remember"> Remember me
<span></span>
</label>
</div>
<div class="col m--align-right m-login__form-right">
Forget Password ?
</div>
</div>
<div class="m-login__form-action">
<button id="m_login_signin_submit" class="btn btn-focus m-btn m-btn--pill m-btn--custom m-btn--air m-login__btn">Sign In</button>
</div>
</form>
And my meta tag with the CSRF token is correct.
When I log in and the ajax receives the response 'success' it's supposed to automatically redirect the user to the dashboard. When it fails it will flip the else statement and show an error ("Incorrect Credentials......") and so forth.
Temporarily you can see my issue until I cannot provide public access:
https://my.distincttrack.com/admin/login
email: jarrod#distincttrack.com
pass: admin

Laravel + Vue unable to save data to my database

I'm trying to save data from my vue component to database but it will just say 500 (internal server error ) on my dev tools.
I tried one by one deleting my code to see where it fails everything will work fine until the I added the save(); function to my database
Vue Component
<template>
<form #submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="post" id="post" v-model="fields.post" />
<div v-if="errors && errors.post" class="text-danger">{{ errors.post[0] }}</div>
</div>
<button type="submit" class="btn btn-primary">Send message</button>
<div v-if="success" class="alert alert-success mt-3">
Message sent!
</div>
</form>
Vue COmponent Script
<script>
export default {
data() {
return {
fields: {},
errors: {},
success: false,
loaded: true,
}
},
methods: {
submit() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post('/adminquickannc', this.fields).then(response => {
this.fields = {}; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
},
}
</script>
Controller // My controller code to save it on the database
use App\Post;
use Illuminate\Http\Request;
public function store(Request $request)
{
// Validation
$this->validate($request, [
'name' => 'required',
'post' => 'required|max:500|min:10'
]);
// Variables we needed
$name = $request->input('name');
$post = $request->input('post');
// Saving the post to database
$post = new Post();
$post->name = $name;
$post->post = $post;
$post->save();
}
I expect this code to save data to my database, is this way of saving it safe? and can you guys give me tools where errors like this can be more specific so i can understand where it fails Thank you in advance guys!

Laravel VueJS Axios send array to controller

I have a laravel 5.4 application which uses VueJS 2.0 for the front end.
I'm trying to post the visitors array to the controller after populating on the page but when I return the array from the controller the data isn't there.
I can't see for the life of me what I'm doing wrong? What's interesting is if I send two visitors through I get two empty arrays returning from my controller so the number of visitors is working it's just not capturing the data.
My vue instance.
<script>
new Vue({
el: '#app',
data: {
visitors: [],
visitor: [],
},
methods: {
addVisitor() {
this.visitors.push(this.visitor);
this.visitor = [];
},
storeVisit()
{
axios({
method: 'post',
url: '/visit/new',
data: {
visitors: this.visitors
}
});
}
},
});
</script>
My HTML page
<p>Visitors</p>
<div class="columns">
<div class="column">
<input class="input" placeholder="First Name" v-model="visitor.first">
</div>
<div class="column">
<input class="input" placeholder="Last Name" v-model="visitor.last">
</div>
<div class="column">
<input class="input" placeholder="Company" v-model="visitor.company">
</div>
<div class="column">
<input class="input" placeholder="Email" v-model="visitor.email">
</div>
<div class="column">
<button class="button is-primary" #click="addVisitor()">Add</button>
</div>
</div>
I've then got a button that actions the storeVisit() method.
<button class="button is-primary" #click="storeVisit">Save Visit</button>
My controller waiting the post request
public function store(Request $request)
{
return $request->visitors;
}
My response
{"visitors":[[],[]]}
visitor should be an object, not an array
data: {
visitors: [],
visitor: {}, // <- object here
},
addVisitor() {
this.visitors.push(this.visitor);
this.visitor = {}; // <- reset to an empty object
},

Pass form data to laravel controller using AngularJS

I have a simple code here and want to pass data to the laravel controller so I can store it to the database. My codes are:
AccountController.php
public function store(Request $request)
{
Account::create(array(
'email' => $request->get('email'),
'name' => $request->get('text'),
'age' => $request->get('age'),
));
return ['success' => true];
}
Blade
<form ng-submit="newAccount()">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" ng-model="accountData.email">
</div>
<div class="form-group">
<label for="fullname">Full Name</label>
<input type="email" class="form-control" id="fullname" ng-model="accountData.name">
</div>
<div class="form-group">
<label for="age">age</label>
<input type="email" class="form-control" id="age" ng-model="accountData.age">
</div>
</form>
app.js
var app = angular.module('accountsApp', []);
app.controller('accountsCtrl', function($scope, $http) {
$scope.newAccount = function() {
//add data
$http.post('/api/accounts',
{
//what will I put here to get the textbox values?
}).
.success(function(response) {
scope.accounts = response;
})
.error(function(response) {
console.log(response);
});
};
});
As you can see in my app.js, I'm stuck on how to get the data from the textbox in my blade. Is there an easy way to do this? Thank you.
Pretty easy, you can just add an object to pass with the POST request. Laravel will pick these variables up 1 to 1.
var app = angular.module('accountsApp', []);
app.controller('accountsCtrl', function($scope, $http) {
$scope.newAccount = function() {
//add data
$http.post('/api/accounts',
{
email: $scope.accountData.email,
text: $scope.accountData.text,
age: $scope.accountData.age
}).
.success(function(response) {
scope.accounts = response;
})
.error(function(response) {
console.log(response);
});
};
});

Categories