$http.post() does not work - (AngularJS) - 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?

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>

TokenMismatchException in VerifyCsrfToken in Laravel 5.1 + angular

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

how to set function or get value from parameters on select change in angular.js

I am newer in anguler and want a value on change from select option and want to update status of particular ID. I have setup some code but this is not working. can you help me.
fetch data and get it on data and after that setup a select box
<select ng-model="newStatus" ng-change="changeNewStatus(data.id, data.message_status)">
<option value="1" ng-selected="data.message_status == 1">New</option>
<option value="2" ng-selected="data.message_status == 2">Closed</option>
</select>
now i want to print it here {{selectedResult}}
below is my controller where i want to call this function
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
here is my full code
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$http.get('api/v1/loadMessage.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 25; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
you can use ng-options directive :
partial:
<div ng-app="test">
<div ng-controller="TestController">
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected">
<option value="">Select</optipn>
</select>
<span>{{selected}}</span>
</div>
</div>
js:
var app = angular.module("test", []);
app.controller("TestController", ["$scope", function($scope) {
$scope.items = [{
id: 1,
label: 'aLabel'
}, {
id: 2,
label: 'bLabel'
}];
}]);
example
http://codepen.io/anon/pen/MaRMPz

ng-select with lazy population

It's an edit form with parent record first populated then dependent select list is populated, and then it's expected the value from parent record pre-select the combo box.
html
<select ng-model="data.trackId" >
<option ng-repeat="track in tracks" value="{{track.id}}">{{track.name}}</option>
initial result once parent record is pulled.
if(data) {
this.$scope.data.id = data.id;
this.$scope.data.name = data.name;
this.$scope.data.room = data.room;
this.$scope.data.start = data.start;
this.$scope.data.end = data.end;
this.$scope.data.dayId = data.day_id;
this.$scope.data.trackId = data.track_id;
this.$scope.data.color = data.color;
this.$scope.data.description = data.description;
this.$scope.$apply();
this.$element[0].removeAttribute("style");
}
//later track results were pulled
trackResult: function(data, status, headers, config) {
for(var i=0; i<data.length; i++) {
this.$scope.tracks.push(data[i]);
}
this.$scope.$apply();
},
Problem:
List gets populated from the second call trackResult but default value from the $scope.trackId never sets the combo box to a value.
Edit: Controller Body
controller: function($scope, $element) {
var self = this;
this.$scope = $scope;
this.$element = $element;
this.$scope.data = {};
this.$scope.days = [];
this.$scope.tracks = [];
this.$scope.submit = function() {self.submit()};
this.$scope.cancel = function() {self.cancel()};
},
Edit : Updated with setting the data from outside the scope (OP request)
Use ng-options & ng-model
this is how i think it should be done in angularjs.
use the built in databinding capabilities to simplify your code and make it less complicated
for binding a list into a <select> and controlling the selected item, this snippet below should do the trick.
http://jsfiddle.net/72em40j4/
js
var myapp = angular.module('myapp', []);
myapp.controller('Ctrl', function ($scope) {
$scope.options = [];
$scope.selectedOption = null;
});
html
<script>
function clickFromOutside() {
var controllerElement = document.getElementById('container');
var controllerScope = angular.element(controllerElement).scope();
var firstTrack = {
id: 1,
first: 'First',
last: 'Track'
};
var secondTrack = {
id: 2,
first: 'Second',
last: 'Track'
};
controllerScope.options.push(firstTrack);
controllerScope.options.push(secondTrack);
controllerScope.selectedOption = secondTrack;
controllerScope.$apply();
}
</script>
<button onclick="clickFromOutside();">outside</button>
<div ng-app="myapp">
<fieldset id="container" ng-controller="Ctrl">
<select ng-options="p.first + ' ' + p.last for p in options" ng-model="selectedOption"></select> <pre>{{ selectedOption }}</pre>
</fieldset>
</div>

ngdialog not update table after create new item

I'm using AngularJS and have the following problem with ngdialog.
I have a function that opens a dialog and then saving dialog form elements which are then displayed in a table.
The table is updated without reloading the page, but to reopen the dialog goes with previous data.
I want to add a new item without reloading the page. Now I do, but I have to reload the page because when recreating another I get with the new data from the previous dialog
var app = angular.module('AlarmsAddOn', ['ngTable', 'ngDialog'])
app.controller('AlarmsAddOnCtrl', function($scope, $http, $filter, ngTableParams, datas, ngDialog, tags, tagIndex, $timeout){
var self=this;
//initializing $scope
$scope.data=datas;
$scope.tagss=tags;
$scope.tagIndex=tagIndex;
$scope.tableParams = new ngTableParams({
page: 1,
count: 10,
filter: {
message: ''
},
sorting: {
tag_id: 'asc'
}
},
{
total: $scope.data.length,
counts:[],
getData: function($defer, params) {
var orderedData = params.sorting() ?
$filter('orderBy')($scope.data, params.orderBy()) :
$scope.data;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
//edit tag settings
self.edit_addon = function(key){
$http.post('/', key).then(function(results){
if (results.status==201)
{
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings has been updated. The new Trigger Value is: "+key.value;
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
};
//delete tag settings
self.delete_addon = function(key){
if(confirm("Are you sure to remove the tag settings")){
var url='/'+key.tag_id+'/'+key.trigger;
$http.delete(url).then(function (results) {
console.log(results);
if (results.status==200)
{
for(var i=0; i<$scope.data.length; i++)
{
if($scope.data[i].tag_id == key.tag_id && $scope.data[i].trigger == key.trigger)
{
var p=i;
}
}
$scope.data.splice(p,1);
$scope.tableParams.reload();
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings of "+key.tag_name+" has been deleted";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000)
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
}
};
//create new tag settings
self.savetag = function () {
$scope.tag=self.tag;
$http.post('/', $scope.tag).then(function (results) {
if (results.status==201)
{
$scope.data.unshift(self.tag);
$scope.tableParams.reload();
// window.location.reload();
}
else
{
}
});
ngDialog.close();
};
//show form to add new tag settings
self.insert_modal_windows_addon = function()
{
ngDialog.open({ template: '/assets/insert.html', controller: 'AlarmsAddOnCtrl', scope: $scope, cache: false});
};
});
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Add New Tag</h3>
<form name="tag_form" ng-submit="AOC.savetag()" >
<select class="form-control" name="tagid" placeholder="Tag Id" ng-model="AOC.tag.tag_id">
<option value="" disabled selected>Tag Name</option>
<option ng-repeat="k in tagss" value="{{k}}">{{tagIndex[k]}}</option>
</select>
<select class="form-control" name="tagtriggertype" placeholder="Trigger Type" ng-model="AOC.tag.trigger" style="margin:20px auto;">
<option value="" disabled selected style="color:#333;">Trigger Type</option>
<option value="hight">hight</option>
<option value="low">low</option>
</select>
<input type="number" class="form-control" name="tagtriggervalue" placeholder="Trigger Value" ng-model="AOC.tag.value", style="margin:20px auto;"/>
<button class="btn btn-sm btn-primary" type="submit">
<span class="glyphicon glyphicon-floppy-save"></span>
Submit
</button>
</form>
</div>
</body>
</html>

Resources