Send a JS variable to a specific Symfony route - javascript

I have a Symfony 3 project with Angular JS in front.
The project is about taking an URL with specific XML content, send it to SF3, do some manipulation, and send the final result to Angular JS.
I just want to catch my url variable in my Symfony Controller.
app.js
var app = angular.module("test", []);
app.controller("testCtrl", ['$scope', '$http', '$window', function($scope, $http, $window) {
$scope.getMyXML = function() {
$http.get($scope.urlSubmitted)
.success(function(data, status, headers, config) {
$http({
method: 'POST',
url: Routing.generate('f_api'), //FOSJsRoutingBundle
headers: {},
params: {},
data: {urlToParse:$scope.urlSubmitted}
}).then(function successCallback(response) {
console.log('Sended to SF3');
}, function errorCallback(response) {
console.log('NOT sended to sf2');
});
})
.error(function(data, status, headers, config) {
alert('!! XML GET ERROR !!');
})
}
}]);
Symfony controller action
class MyController extends Controller
{
public function indexAction(Request $request)
{
$serializer = $this->get('jms_serializer');
$data = $request->request->get('urlToParse');
//var_dump($data);
//die;
return $this->render('MyBundle:My:index.html.twig');
}
public function apiAction(Request $request)
{
$data = $request->request->get('urlToParse');
var_dump($data);
die;
return new JsonResponse();
}
}
And last, my routing.yml
f_home:
path: /
defaults: { _controller: MyBundle:My:index }
f_api:
path: /api/
defaults: { _controller: MyBundle:My:api }
options:
expose: true
The apiAction is never lanched, despite of the angular http post on it...
Thanks !

Try this:
data: {'urlToParse':$scope.urlSubmitted}
then:
$data = $request->request->get('urlToParse');

Related

How to call php file via factory/service method using Angular.js

I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);

Sending data stored on a service

I have the following controller and service
angular
.module('myApp')
.controller('Spliptter', Spliptter) // Controller
.service('SplitService', SplitService); //Service
function Spliptter($scope, SplitService){
var result = SplitService.phoeNoSplit($scope.phoneNumber.number); //Phone Data
$scope.area: result['area'];
$scope.country: result['country'];
}
function SplitService() {
this.phoeNoSplit = function(phoneNumber) {
var area = phoneNumber.substring(0, 3); //Info that I want to send
var country = phoneNumber.substring(3, 10); //Parse
return {
'area': area,
'country': country
}
}
}
Also I have a form where I use to send the area code and the country code.
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope) {
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone,
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}
But, I dont know whats the problem. I'm new in angular.
Please read angular docs first so that you will get better understanding how controller and service works.
Here issue is you are trying to access the scope of Spliptter controller into formController controller which will never possible.
If you have to use that scope values in formController then you will have to initialise those scope values in formController itself.
Refer below code:
formController
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope, SplitService) {
var result = SplitService.phoeNoSplit($scope.phoneNumber.number);
$scope.area: result['area'];
$scope.country: result['country'];
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone, // am not sure from where you are getting it
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}

AngularJS: console.log does not display anything

I wrote a controller for login page. Here is my controller:
var authApp = angular.module('loginApp', [])
authApp.controller('LoginCtrl', ['$scope', '$location', 'loginFactory', function($scope, $location, loginFactory){
$scope.authenticate = function() {
loginFactory.login($scope.username, $scope.password)
.then(function(response) {
console.log(response.$statusText);
}, function errorCallBack(response) {
console.log(response.$statusText);
});
}
}]);
My service:
authApp.factory("loginFactory", function ($http) {
return{
login: function(username, password) {
var data = "username="+username+"&password="+password+"&submit=Login";
return $http({
method: 'POST',
url: 'http://localhost:8080/login',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
});
}
When I debug the code, authentication seems successful and it did get into then function. However nothing displays in console. And I got a warning(?) saying undefined for the line console.log(response.$statusText);. It is not an error since it is not red. Why doesn't it print out anything?
Use response.statusText not response.$statusText. The documentation for AngularJS $http requests lists statusText as one of the properties of the response object - https://docs.angularjs.org/api/ng/service/$http

Async nature of AngularJS with digest/apply

I've often had a problem where I had a scope variable set up in a parent controller, and the child controller calls this scope variable. However, it calls it before the function has been able to set the scope element, causing it to return undefined. Example:
Parent Controller:
module.controller('parent', '$scope', '$http', function ($scope, $http) {
$scope.init = function(profileID, profileViewStatus) {
//Initiiaze user properities
$http.get(requestUserInformationGetURL + profileID)
.success(function(profile) {
$scope.profile = profile;
$scope.userID = profile.user_id;
$scope.username = profile.username;
console.log($scope.userID);
})
.error(function() {
exit();
});
}
Child Controller:
module.controller('child', function($scope, $http, fetchInfo) {
console.log($scope.userID);
//Fetch the HTTP POST data for the user profile
var promise = $http({
method: "post",
url: fetchInfo,
data: {
user_id: $scope.userID //From the parent controller
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
promise.then(function(successResponse) {
//Populate the scope, log the data
console.log(successResponse);
$scope.data = successResponse.data;
}, function(error) {
alert(error);
});
HTML:
<div ng-controller="parent" init="init('<?php $user_id;?>')">
<div ng-controller="child">
</div>
</div>
What often happens is that the userID will be reported back as undefined in the child controller, but then right after, it will be reported back as defined in the parent controller. Obviously, the child controller using the $scope.userID is being called before the init function in the parent controller is complete. How do I force AngularJS to wait in the child controller until the init function is complete? I've tried something like:
if (!$scope.userID) {
$scope.$digest();
}
But it didn't work and I don't think it's the correct syntax. I guess, I don't fully understand the Asycn nature of AngularJS and this occurs multiple times. How do you control the DOM loading elements to solve something like this problem?
Proper way in this case would be to use dedicated service to handle async operations, requests, data caching, etc. But since you don't have service layer yet, I will propose simple Promise-based solution using controller scope promise object.
Check you modified code:
module.controller('parent', ['$scope', '$http', function ($scope, $http) {
$scope.init = function (profileID, profileViewStatus) {
$scope.profilePromise = $http.get(requestUserInformationGetURL + profileID).success(function (profile) {
$scope.profile = profile;
$scope.userID = profile.user_id;
$scope.username = profile.username;
})
.error(exit);
}
}]);
module.controller('child', function($scope, $http, fetchInfo) {
// Fetch the HTTP POST data for the user profile
$scope.profilePromise.then(function() {
return $http({
method: "post",
url: fetchInfo,
data: { user_id: $scope.userID },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
})
.then(function(successResponse) {
console.log(successResponse);
$scope.data = successResponse.data;
}, function(error) {
alert(error);
});
});
As you can see, parent controller init method is still called, but now it immediately sets scope property profilePromise, which is accessible in child controller.
Child controller uses then method of the parent controller profilePromise object, which guaranties that $http request using $scope.userID will fire after profile is already available.
Generally you would use a route resolve with the UI Router to ensure the work is done before either controller is constructed. Child states automatically have access to the resolves of their parent.
//Router configuration
.state('app.inspections.list', {
url: '',
templateUrl: 'Template/parent',
controller: "Parent as vm",
resolve: {
profile: ['$http', function ($http) {
return $http.get(requestUserInformationGetURL + profileID)
.success(function(profile) {
console.log(profile.userID);
return profile;
})
.error(function() {
exit();
});
}]
}
}).state('parent.child', {
url: 'child',
templateUrl: 'Template/child',
controller: "Child as vm"
})
//parent controller
module.controller('parent', '$scope', 'profile', function ($scope, profile){
$scope.profile = profile;
$scope.userID = profile.user_id;
$scope.username = profile.username;
}
//child controller
module.controller('child', 'profile', function($scope, $http, fetchInfo, profile){
console.log(profile.userID);
//Fetch the HTTP POST data for the user profile
var promise = $http({
method: "post",
url: fetchInfo,
data: {
user_id: profile.userID //From the parent controller
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
promise.then(function(successResponse) {
//Populate the scope, log the data
console.log(successResponse);
$scope.data = successResponse.data;
}, function(error) {
alert(error);
});
you can use promise ($q service) :try using this code:
parent controller :
$scope.init = function(profileID, profileViewStatus) {
var deferred = $q.defer();
$http.get(requestUserInformationGetURL + profileID)
.success(function(profile) {
$scope.profile = profile;
$scope.userID = profile.user_id;
$scope.username = profile.username;
deferred.resolve($scope.userID);
console.log($scope.userID);
})
.error(function() {
deferred.reject('error');
exit();
});
return deferred.promise;
}
Don't call init method in parent contrller.
in child controller:
$scope.init().then(function(userID){
var promise = $http({
method: "post",
url: fetchInfo,
data: {
user_id: userID //From the parent controller
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
promise.then(function(successResponse) {
//Populate the scope, log the data
console.log(successResponse);
$scope.data = successResponse.data;
}, function(error) {
alert(error);
});
})
.catch(function(error){
console.log('error');
})
Your problem might be that $.get is being called asynchronously, which is the default behavior. Your init method might actually be called in the order you're expecting but what's happening is:
Parent init is called
$.get is called, but the server's response is non-instantaneous
Child init is called
GET data bounces back from the server
$.get(..).success(function(data){...}); is called to deal with the data
I'd suggest what other people are, using promises to defer execution.

Using Parse.com REST-API with AngularJS

I would like to use Parse with AngularJS. I'm a new one in both...
I'm trying to create a new user but i receive the error "bad request".
Here is my controller (linked to two input html tags):
var myAppControllers = angular.module('myApp.controllers', []);
myAppControllers.controller('SignUpCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.results = []
$scope.signUp = function() {
$http({method : 'POST',
url : 'https://api.parse.com/1/users',
headers: { 'X-Parse-Application-Id':'xxx', 'X-Parse-REST-API-Key':'xxx'},
params: {
where: {
username: $scope.username,
password: $scope.password
}
}} )
.success(function(data, status) {
$scope.results = data;
})
.error(function(data, status) {
alert("Error");
})
}
}]);

Categories