TokenMismatchException in VerifyCsrfToken in Laravel 5.1 + angular - angularjs

I have Laravel 5.1 + angular form sending JSON request when user want to send mail from website feedback form.
I did my form according to documentation here https://laravel.com/docs/master/csrf and anyway I get error message TokenMismatchException in VerifyCsrfToken.php line 53:
I found a lot of topics on stackoverflow, but no real solution.
Is there?
in header of my layout I have
<meta name="csrf-token" content="{!! csrf_token() !!}">
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
then in my form I have this
<form name="callback" ng-controller="callbackController" role="form" class="" enctype="multipart/form-data">
{!! csrf_field() !!}
...
...
<button type="submit" class="btn btn-primary pull-right" ng-click="submit(callback.$valid)" ng-bind="submittext" ng-class="{ 'btn-danger': callback.name.$touched && callback.name.$invalid || callback.tel.$touched && callback.tel.$invalid, 'btn-success': callback.name.$touched && callback.name.$valid && callback.tel.$touched && callback.tel.$valid, }">Send</button>
</form>
here is the code of my angular
angular.module('myapp', ['ngMessages', 'angularFileUpload'])
.controller('callbackController', function($scope, $http, $timeout) {
$scope.formData = {};
$scope.url = '/';
$scope.submittext = 'Отправить';
$scope.submit = function(isValid) {
if (isValid) {
$scope.submittext = 'Отправляем...';
$http.post($scope.url,
{
"formname": "callback",
"name": $scope.name,
"tel": $scope.tel,
"time": $scope.time,
"email": $scope.email,
"msg": $scope.msg
}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
});
$timeout(function() {
$('#callback').modal('hide');
$scope.submittext = 'Отправить';
$scope.name = null;
$scope.tel = null;
$scope.time = null;
$scope.email = null;
$scope.msg = null;
$scope.callback.$setPristine();
$scope.callback.$setUntouched();
}, 1000);
} else {
$('.errors').modal('show');
}
}
})

The problem with your code is that the second line in the form
{!! csrf_field() !!}
generates some code like:
<input type="hidden" name="_token" value="ZwiQQ3BJFbWMr4goixtcklwGvpxIeN8vkWNinHIL">
which is not what you need.
Just like the link you have posted, you need to put the following line in the head area:
<meta name="csrf-token" content="{{ csrf_token() }}">
because using ajax, you are adding a header which picks its value by looking for a meta tag which has the name csrf-token

Related

angularjs,I'm using ng-repeat loop option,value="number:1"

enter image description here
This situation causes the form submission parameter to become “number:1”。
Could you tell me why this problem happened?
javascript code as follows:
app.controller("Controller", function($scope,$http,$filter){
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
}
jsp code as follows:
<select name="positionId" class="form-control"
ng-model="data.userGroup.GroupId" >
<option ng-repeat="p in userGroups" value="p.GroupId"
ng-value="{{p.GroupId}}">{{p.name}}
</option>
</select>
app.controller("Controller", function($scope,$http,$filter){
var userGroups={};
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
//$scope.data = response.data;
$scope.userGroups.GroupId = "" + response.GroupId;
}, function errorCallback(response) {
alert("00");
});
}
After getting the values in the JS controller file, write dropdown list in the view page as below:
<select name="positionId" class="form-control"
ng-model="userGroups.GroupId" >
<option ng-repeat="p in userGroups" value={{p.GroupId}}>
{{p.name}}
</option>
</select>
If you want to set a particular value in a dropdown list to show while loading the dropdown then simply assign the value to the ng-model in the respective js controller file as below:
$scope.userGroups.GroupId = "" + response.GroupId; // based on your specific data
(Note: please check I have set ng-model as userGroups.GroupId and assigned userGroups={}; to initialize the userGroups to be used in the view page.)
Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.js"></script>
</head>
<body data-ng-app="role" data-ng-controller="fooController">
<select class="form-control"
ng-model="user.roles"
ng-options="role.id as role.name for role in roles"
required=""></select>
</body>
</html>
<script>
var app = angular.module('role', []);
app.controller('fooController', function($scope){
$scope.roles = [{id:0, name:"Select"},{id:1, name:"Administrator"}, {id:2, name: "Student"}];
$scope.user = {};
$scope.groupId = 1;
$scope.user.roles = $scope.roles[$scope.groupId].id ;
});
</script>
</html>

$http.post() does not work - (AngularJS)

I am trying to create a form with a dropdown input field and a submit button in AngularJS. Everything works fine except the output is empty xD. I am using <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>. And if it's any help on server side I am using PHP Version 5.5.36-1+donate.sury.org~trusty+1.
Here's the Angular code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.myTxt = "You have not clicked submit, yet!";
$scope.show_result = false;
$scope.myFunc = function() {
$scope.myTxt = "You clicked submit!";
$scope.show_result = true;
}
$scope.categories = [
{"value": 0, "categoryname": "standard"},
{"value": 1, "categoryname": "premium"},
{"value": 2, "categoryname": "gold"}
];
$scope.submitData = function() {
$scope.category = {};
console.log($scope.category);
var jsonString = JSON.stringify($scope.category);
$http.post('ServerController.php', jsonString, {'Content-Type': 'application/x-www-form-urlencoded'})
.success(function(data, status) {
$scope.status = status;
$scope.data = data;
});
}
});
Here is the ServerController.php :
$jsonString = file_get_contents('php://input');
$form_data = json_decode($jsonString, true);
if ($form_data != null) {
echo 'Success!!!';
var_dump($form_data);
} else {
echo 'Sorry!!!';
var_dump($form_data);
}
Here is the HTML:
<body ng-app="plunker">
<form ng-submit="myFunc()" ng-controller="MainCtrl">
<label><b>Category:</b></label>
<select ng-model="category" ng-options="x.categoryname for x in categories track by x.value">
<option value="">Choose a Category</option>
</select>
<p><b>Model:</b> {{category}}</p>
<input ng-click="submitData()" type="submit" value="Submit"></input>
<i>{{myTxt}}</i>
<p ng-show="show_result"><b>Submitted result:</b> {{data}}</p>
</form>
</body>
Here is how the form looks on page load:
This is after you select category in the dropdown:
And finally after clicking submit:
Note: The server controller is sending the output in Submitted result ie. Sorry!!!<pre class='xdebug-var-dump' dir='ltr'> <b>array</b> <i>(size=0)</i> <i><font color='#888a85'>empty</font></i> </pre>
Any ideas?

Angularjs checkbox initialization issue using json object

So i have a checkbox page barely working, the issue is when i first start this page, the checkbox is not checked, even though i try to initialize it from backend node server. No error in browser debugger though.
in the server mye,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var formDataArray = { "formDataObjects": [
{"flagName":"myStuff1", "flagVal":0},
{"flagName":"myStuff2", "flagVal":1}
]};
res.contentType('application/json');
res.send(formDataArray);
});
app.post('/2setMyDiagValue', function(req, res)
{
......
}
in the client mye,
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
$scope.message = 'SID Diagnostics';
// using http.get() to get existing my setting from server mye
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
i did try to modify ng-checked like this and the checkbox did show checked.
ng-checked="true"
well, just used "res.json" in the node.js side and made it work, guess i just don't have time to learn, while this fxxking company gave me a tough schedule

Angularjs model not updated when switching between users at login

I need the following functionality: When a user goes to the login form, the browser should auto fill the username and password.
My implementation works (on FF and Chrome) but, there is this bug (not consistent) where the model data does not get updated correctly when switching between users. This means that I log in with user ONE, then log out, and enter the credentials for user TWO, but after I click the login button, I'm still logged in with user ONE.
The login form looks like this:
<form class="form-horizontal" ng-submit="login(credentials)">
<fieldset>
<div class="form-group" ng-class="{'has-error' : validationErrors.email}">
<div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input type="email" name="email" autocomplete="on" ng-model="credentials.email" class="form-control input-lg input-round text-center" placeholder="Email" >
<span class="help-block" ng-if="validationErrors.email">{{ validationErrors.email.0 }}</span>
</div>
<div class="form-group" ng-class="{'has-error' : validationErrors.password}">
<div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light">
<span class="glyphicon glyphicon-lock"></span>
</div>
<input type="password" name="password" autocomplete="on" ng-model="credentials.password" class="form-control input-lg input-round text-center" placeholder="Password" >
<span class="help-block" ng-if="validationErrors.password">{{ validationErrors.password.0 }}</span>
</div>
<div class="form-group">
<input type="submit" value="Sign in" class="btn btn-primary btn-lg btn-round btn-block text-center">
</div>
</fieldset>
</form>
The login controller contains something like:
// Login Controller
app.controller( 'LoginCtrl', ['$rootScope','$scope', '$state', 'AppUser', 'Auth',
function($rootScope, $scope, $state, AppUser, Auth){
console.log("LoginCtrl");
$scope.credentials = {
"email" : "",
"password": ""
};
$scope.redirectAfterLogin = function() {
// set user data
AppUser.setUserData($scope.user);
...
}
// Login attempt handler
$scope.login = function(data) {
data = {'user':data};
Auth.login(data,
function(response) {
$scope.user = response.data;
...
},function(response){
$scope.validationErrors = {
"email" : [],
"password": []
};
...
}
);
};
}]);
Logout:
// logout
$scope.logout = function() {
// remove attempted URL, if any
AppUser.removeAttemptUrl();
data = {'user':
{
'email': $scope.user.email
}
};
Auth.logout(data,
function(){
AppUser.unSetUserData($scope.user); // se method below
$state.go(ApplicationState.LOGIN);
},
function(){
console.log("Logout failed");
});
}
angular.module('app.service').factory('AppUser', [
'$window', '$rootScope', 'LocalStorage', 'appConfig', '$injector', '$location',
function($window, $rootScope, localStorage, appConfig, $injector, $location){
// Redirect to the original requested page after login
var redirectToUrlAfterLogin = { url: '' };
var userKey = "AppUser";
var userData = {};
angular.element($window).on('storage', function(event) {
if (event.key === userKey) {
$rootScope.$apply();
}
});
return {
/**
* Redirect to the original requested page after login
* - we need to be able to save the intended URL, request it, remove it and redirect to it
*/
saveAttemptUrl: function() {
if ($location.path().toLowerCase() != ApplicationState.LOGIN) {
redirectToUrlAfterLogin.url = $location.path();
}
else {
redirectToUrlAfterLogin.url = '/';
}
},
getAttemptedUrl: function() {
return redirectToUrlAfterLogin.url;
},
removeAttemptUrl: function() {
// re-initialize URL
redirectToUrlAfterLogin = { url: '' };
},
redirectToAttemptedUrl: function() {
$location.path(redirectToUrlAfterLogin.url);
},
/**
* Returns the current user's state
* #returns {boolean}
*/
isAuthenticated: function() {
userData = JSON.parse(localStorage.get(userKey) || '{}').userData;
if (!this._isSessionExpired()) {
if (userData !== undefined){
return !!(userData.id !== null && userData.email);
}
else{
return false;
}
}
else{
if (userData !== undefined){
var data = {
'user':{
'email': userData.email
}
}
// we use $injector to avoid Circular Dependency which is thrown by injecting the $api service
$injector.invoke(['$api', function($api){
$api.auth.logout(data).success(function(result){
userData = {};
localStorage.remove(userKey);
});
}]);
return false;
}
}
},
getUserData: function() {
return userData;
},
setUserData: function(data) {
userData = data;
localStorage.set(userKey, JSON.stringify({
userData: data,
stamp: Date.now()
}));
},
unSetUserData: function() {
userData = {};
localStorage.remove(userKey);
},
_isSessionExpired: function() {
var session = JSON.parse(localStorage.get(userKey) || '{}');
return (Date.now() - (session.stamp || 0)) > appConfig.sessionTimeout;
},
userData : userData
};
}] );
Any ideas on why this is happening?
After you logout check the localStorage with the browser inspector.
Probably you will find some variable that you didn't clear.
So just clear the storage and it should be fine.
To clear the storage use:
localStorage.clear();
One additional problem it could be you didn't clean the $rootScope if you didn't refresh all the data are still in there.
Is this the problem? userKey doesn't seem to be defined in the code you've showed.
// add userKey param
unSetUserData: function(userKey) {
userData = {};
localStorage.remove(userKey);
},

Can't send a POST request with $http in Angular - ReferenceError: $http is not defined

So I keep getting this ReferenceError: $http is not defined, even though I have included $http in the controller, which seems to be the most common cause of this error message. I've tried also passing $http into the function itself, but that doesn't solve it.
I feel like I am missing something SUPER obvious, so any help would be much appreciated, thank you!
I've included the entire script, just for clarity's sake. You can see the post request towards the end of the script, inside the finaliseDay function.
Thanks!
Here is the error:
ReferenceError: $http is not defined
at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c
Here is the HTML first
<!doctype html>
<html ng-app="goalzy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="goalzy.js"></script>
</head>
<body>
<div class="container">
<div class="well">
<h2>Goalzy</h2>
Dev TODO
<ul>
<li>Hook up the API to persist data</li>
</ul>
<div ng-controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining today</span>
<span>You're at {{percentComplete()}}% completion</span>
[ finalise day ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<hr>
<div class="historial" ng-repeat="h in historicalDailyPercentages">
<ul>
<li>Date: {{h.date}}</li>
<li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
<li><div>Tweet it!</div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
And here is the JS:
//Goalzy.js
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];
$scope.historicalDailyPercentages = [];
$scope.addTodo = function() {
if ($scope.todoText != "") {
if ($scope.todos.length < 3) {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
//Save to DB
}
else {
alert("You can only have 3 todos per day!");
$scope.todoText = '';
}
} else {
alert("you must write something");
}
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.percentComplete = function() {
var countCompleted = 0;
angular.forEach($scope.todos, function(todo) {
countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
console.log(countCompleted);
});
var totalCount = $scope.todos.length;
var percentComplete = countCompleted / totalCount * 100;
return percentComplete;
}
$scope.finaliseDay = function(percentComplete) {
alert("You're finalising this day with a percentage of: " + percentComplete);
var today = new Date();
var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) {
return item.date.getFullYear() === today.getFullYear() &&
item.date.getMonth() === today.getMonth() &&
item.date.getDate() === today.getDate();
});
//Confirm that nothing has alreayd been posted for today
if (!alreadyPresent) {
$scope.historicalDailyPercentages.push({
percent: percentComplete,
date: today
});
// Simple POST request example (passing data) :
$http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("data" + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("data" + data);
});
}
else {
alert("You're all set for today - see you tomorrow!");
}
console.log($scope.historicalDailyPercentages);
}
}]);
Provider won't be available inside controller with suffix 'Provider', you can do access them by provider name only here it would be $http only, also remove ;
after config initialization
$httpProvider setting should be done inside the angular config phase
CODE
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
.controller('TodoController', ['$scope', '$http', function($scope, $http) {
//controller code here
}]);
Note: For sure you should remove $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'; line from controller
Working Plunkr
You don't have to use "$httpProvider" in controller, use $http instead.
e.g.
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
As best practice, do not configure provider ($http) in controller. Do it in config section. as below
var app = angular.module('goalzy', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
app.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.title="scope title";
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);
see working plunk at http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/ with your html.

Resources