I'm trying to use AngularJS to POST a form to an API I'm developing.
The form has novalidate, name="addMatchForm", and ng-submit="submit(addMatchForm)". The addMatchForm is as followed:
app.controller('addMatchController', ['$scope', 'players', 'matches', function($scope, players, matches) {
...
$scope.submit = function(form) {
form.submitted = true;
// Make sure we don't submit the form if it's invalid
if ( form.$invalid ) return;
matches.add(form).success(function(data) {
console.log('post result:', data);
})
}
}]);
app.factory('matches', function($http) {
return {
add: function(data) {
return $http.post('/matches', data);
}
}
});
But the weird thing is that each and every input's value becomes an empty object at that point. This is the Form Data from Chrome Developer Tools:
{"a_score":{},"b_score":{},"day":{},"month":{},"year":{},"a_player1":{},"a_player2":{},"b_player1":{},"b_player2":{},"submitted":true}:
I did add the content-type part already.
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
Any ideas?
Try to use $http like this:
return $http({
method: 'POST',
url: '/matches',
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
Related
Let me first preface this by saying...I'm a noob and have been pouring over documentation already but I have not found a resolution.
I have built a custom report in PowerSchool SIS using AngularJS to form my grid and am using JSON data to fill it. The problem I am currently having is the grid is only populating 100 items even though there are close to 200 record items.
This is my JS:
//Begin Module - Loads AngularJS
define(['angular', 'components/shared/index'], function(angular) {
var attApp = angular.module('attApp', ['powerSchoolModule']);
// var yearid = window.location.search.split("=")[1];
//Begin Controller
attApp.controller('attCtrl', ['$scope', 'getData', '$attrs', function($scope, getData, $attrs) {
$scope.curSchoolId = $attrs.ngCurSchoolId;
$scope.curYearId = $attrs.ngCurYearId;
loadingDialog();
$scope.attList = [];
//Sets definition of the var dataSource to pull PowerQueries
var dataSource = {
method: "POST",
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
data: {yearid},
dataType: "json",
pages:"50",
};
console.log(dataSource);
//Sets definition of the var dataSource to pull from JSON files
console.log('loading dataSource');
//var dataSource= {method: "GET", url: "attendancedata.json"};
getData.getAttData(dataSource).then(function(retData) {
if (!retData.record) {
alert('There was no data returned');
closeLoading();
} else {
console.log(retData);
if (!!retData.record[retData.record.length]) {
// retData.record.pop();
}
var i = retData.record.length;
while (i--) {
retData.record[i].attendance_date = new Date(retData.record[i].attendance_date) // Changes the text of the attendance date to a JS data
}
//Sets scope of attList and attName
$scope.attList = retData.record;
$scope.attName = retData.name;
console.log($scope.attList);
closeLoading();
}
});
}]); //End Controller
//Begins factory and invokes PowerQueries if available, error message will trigger if no data returned
attApp.factory('getData', function($http) {
return {
getAttData: function(dataSource) {
return $http(dataSource).then(function successCallback(response) {
return response.data;
},
function errorCallback(response) {
alert('There was an error returning data');
});
}
}
}); //End Factory
}); //End Module
We have confirmed there is nothing wrong with my datasource. I'm stuck and could use a guiding word. Any advice would be appreciated.
Try to hit the same endpoint using PostMan, maybe the API is not working.
Also I'm not sure if this url is valid:
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade"
I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.
The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.
I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.
This is the original ajax code which came from a public github repo:
(function($) {
window.MarketingCloud = {
env: {},
wsse: new Wsse(),
/** Make the api request */
/* callback should follow standard jQuery request format:
* function callback(data)
*/
makeRequest: function (username, secret, method, params, endpoint, callback)
{
var headers = MarketingCloud.wsse.generateAuth(username, secret);
var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
$.ajax(url, {
type:'POST',
data: params,
complete: callback,
dataType: "text",
headers: {
'X-WSSE': headers['X-WSSE']
}
});
}
};
})(jQuery);
This is the current way the code is being used with pure JS:
MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
data = JSON.parse(response.responseText);
});
I want to convert this to a factory and a controller respectively.
This is what I have done for the factory so far:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return function(username, secret, method, params, endpoint) {
return $http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
},
dataType: 'text',
});
};
}]);
And this is what I have for the controller:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
mainFactory.success(function(data) {
$scope.data = data;
});
}]);
Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.
Here is the factory code:
app.factory('mainFactory', ['$http', function($http) {
var wsse = new Wsse ();
return {
getAnalytics : function (){
$http({
method: 'POST',
url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
data: params,
headers: {
'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
}
})
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
And here is the controller code:
app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
$scope.title = "Inn Site";
$scope.data = mainFactory.getAnalytics();
}]);
trying to send post request using AngularJS in Laravel, I'm having this error message:
Sorry, the page you are looking for could not be found.
JAVASCRIPT
app.controller('main',['$scope','$http','$httpParamSerializerJQLike',function($scope,$http,$httpParamSerializerJQLike) {
$scope.courses = [];
$http({
url: "/afil",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded',"X-Requested-With":"XMLHttpRequest"},
data: $httpParamSerializerJQLike()
}).success(function(res) {
console.log(res);
// $scope.courses = res;
}).error(function(res) {
});
}]);
routes.php
Route::post('/afil', function () {
return 'Hello World';
});
check if your form action url is correct , if you are using a group prefix in you routes don't forget to include it in the form action url
Might be you will have to first set the header in angular module. Then you will make the http request.
var app = angular.module('App', [], ['$httpProvider', function($httpProvider) {
//Setting headers
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.headers.common['X-Requested-With'] = "XMLHttpRequest";
$httpProvider.defaults.headers.post['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
}]);
app.controller('main',['$scope','$http','$httpParamSerializerJQLike',function($scope,$http,$httpParamSerializerJQLike) {
$scope.courses = [];
$http({
url: "/afil",
method: "POST",
data: $httpParamSerializerJQLike()
}).success(function(res) {
console.log(res);
// $scope.courses = res;
}).error(function(res) {
});
}]);
Hope this will help you.
I use AngularJS for my application to send multiple requests to the server. Here is an example of my code
HTML
<body ng-controller="AccessCtrl">
Javascript
mainApp.factory('authService', function ($rootScope, $http) {
return {
access: function () {
$http({
method: 'POST',
url: some_url,
data: 'grant_type=client_credentials',
}).success(function (response) {
console.log(response);
$rootScope.access_token = response.access_token;
});
}
}
});
controllersApp.controller('AccessCtrl', ['FactoryModule', function (FactoryModule) {
var testServices = FactoryModule('services');
testServices.authService.access();
}]);
And here is my console:
enter image description here
I have 2 requests from index and from angular initiators. How to fix this? I want 1 request to get access token.
I have a situation where I need to consume a restful web service in AngularJS using GET method by allowing it to accept slash "/" character in uri parameter.
Normally "/" slash, creates a different end point and service doesn't give the required response and I need to consume the RESTful web service where the parameter should be passed as string.
Scenario to be considered:
Sample URL: http://hostname/servicename/{parameter}
where parameter should be a string and Should be valid for below sample inputs
a
12
12/15
126/567
I am using below code
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url){
return $http({
method: 'GET',
url: url,
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}])
controller.js
var url = "http://hostname/servicename/" + paramId + "";
dataService.getData(url).then(
function(response) {
// Response stuff here
}
)
NOTE: I have to manage all things at client side and don't have access to server side code of web service.
Encode the parameter like this.
encodeURIComponent(paramId)
Otherwise replace / with '%2f'
Have u tried params object instead passing the parameter directly in the url?
If no.. just pass the parameter as shown below.
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url, paramId){
return $http({
method: 'GET',
url: url,
params:{
"paramId" : paramId
},
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}]);
controller.js
var url = "http://hostname/servicename";
dataService.getData(url, paramId).then(
function(response) {
// Response stuff here
}
);
Let me know if this helps!