Submitting a form via Fetch API in Laravel - php

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

Related

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 api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Vue form not sending data in request

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?

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);
});
};
});

Angularjs Image Upload showing empty nested object

I'm a bit confused how to access file data using with angular from a basic form. I'm following a tut on: (https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs) and youtube (https://www.youtube.com/watch?v=vLHgpOG1cW4). They seem to get it right but when I try things seem to go a different way. Anyways here's my HTML form:
<form>
<div class="form-group">
<label for="name">Full Name</label>
<input type="text" ng-model="customer.name" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" ng-model="customer.email" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="file">Image</label>
<input type="file" file-model="customer.file" id="file" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" ng-click="submit()" class="btn btn-primary">Submit</button>
</div>
</form>
And the Directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
And finally the controller:
app.controller('CustomerController', ['$scope','CustomerService', function($scope, CustomerService){
$scope.customer = {};
CustomerService.save($scope.customer);
}]);
When I {{ customer }} in my view I'm getting something like this:
{"name":"Robert DeNiro","email":"robie#godfather.com","file":{}}
It's that empty last "file":{} file object that's causing me problems getting values to post to server.
Here's my Customer Service code:
var CustomerService = function($resource) {
return $resource('advertisements/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
},
save: {
method: 'post',
transformRequest: angular.identity,
'Content-Type': undefined
}
});
};
CustomerService.$inject = ['$resource'];
app.service('CustomerService', CustomerService);
I'm using Laravel 5.1 and its reporting validation errors 'required' on all fields suggesting there's an empty object sent through. Thanks in advance.
I have added a submit() method in CustomerController like this:
$scope.submit = function(){
var file = $scope.customer.file;
console.log('file is ' );
console.log(file.name);
console.log($scope.customer.file);
console.dir($scope.customer.file);
};
And in there you can see I've tried experimenting with console.log() and console.dir() and i seem to get the results. For example if i console.log($scope.customer) or console.dir($scope.customer) it gives me the nested file object with all file details. And its looking like this:
> Object {name: "robert deniro", email: "robie#godfather.com", file: File}
> Object
Notice file: File Therefore I'm able to access the file contents/object within the submit() like this: console.log(file.name) or console.log(file.type) or console.log(file.size). I don't know why I was missing it all this time. I hope someone learn from my mistake.
May be that form requires the attribute enctype="multipart/form-data".

Categories