Symfony 2 Angular JS HTTP POST - angularjs

I have a form that i submit using angularJS http method.
code :
<script>
// define angular module/app
var formApp = angular.module('formApp', []);
// create angular controller and pass in $scope and $http
function formController($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
// process the form
$scope.processForm = function () {
$http({
method: 'POST',
url: 'http://localhost/angular/web/app_dev.php/testcall',
data: $.param($scope.formData), // pass in data as strings
headers: {'Content-Type': 'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
})
.success(function (data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
$scope.errorName = '';
$scope.errorSuperhero = '';
}
});
};
}
</script>
my form :
<div class="container">
<div class="col-md-6 col-md-offset-3">
<!-- PAGE TITLE -->
<div class="page-header">
<h1><span class="glyphicon glyphicon-tower"></span> Submitting Forms with Angular</h1>
</div>
<!-- SHOW ERROR/SUCCESS MESSAGES -->
<div id="messages" class="well" ng-show="message">{% verbatim %}{{ message}}{% endverbatim %}</div>
<!-- FORM -->
<form ng-submit="processForm()">
<!-- NAME -->
<div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name">
<span class="help-block" ng-show="errorName">{% verbatim %}{{ errorName}}{% endverbatim %}</span>
</div>
<!-- SUPERHERO NAME -->
<div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }">
<label>Superhero Alias</label>
<input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader" ng-model="formData.superheroAlias">
<span class="help-block" ng-show="errorSuperhero">{% verbatim %}{{ errorSuperhero}}{% endverbatim %}</span>
</div>
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-success btn-lg btn-block">
<span class="glyphicon glyphicon-flash"></span> Submit!
</button>
</form>
<!-- SHOW DATA FROM INPUTS AS THEY ARE BEING TYPED -->
<pre>
{% verbatim %}{{ formData}}{% endverbatim %}
</pre>
</div>
</div>
my function where i want my form data from the http request :
/**
* #Route("/testcall")
* #Template()
*/
public function testAction() {
var_dump($_POST);
exit;
}
The only thing i get is this url :
http://localhost/angular/web/app_dev.php/test?name=Tommie&superheroAlias=Crawford
So the values from the form are saved in the URL.
But its not in the $_POST variable..
Its looks like that the function testAction never get accessed
How can i fix this?

You have to access data from the request. If you post JSON object like
{
"foo": "bar"
}
Your controller's action should look something like that:
public function postAction(Request $request)
{
$data = json_decode($request->getContent(), true);
$request->request->replace($data);
//echo below should output 'bar'
echo $request->request->get('foo');
//return response
//....
}
more detailed information about that could be found here

Related

angular: form submit with dynamic dropdown list

I have a small form and in that form i have a drop down list. List items are generated dynamically.
$http({
url: 'alljobs.php',
method: "GET",
params: {
uid: viewer_id
}
}).success(function(data) {
$scope.jobss = data.content;
});
Below is the code for form submit.
$scope.formprofile33 = function() {
var allData33 = {
'msg': $scope.msg,
'emp_id': viewer_id,
'job_id': job.job_id,
'job_title': $scope.jobss.SelectedOption.job_title,
// 'job':job,
'user_id': user_id
}
$http({
method: 'POST',
url: 'send_msg.php',
data: allData33,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
if (!data.success) {
$scope.message = data.errors.message;
} else {
$scope.message = '';
alert('Your message has been sent.');
$scope.message = '';
}
});
};
Here is the form.
<form name="formProfile33" method="post" id="formProfile33" role="form" ng-submit="formprofile33()">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<div class="col-xs-10">
<div class="col-xs-12 s_ma">
<select id="job" name="job" class="search_color selectors form-control" ng-model="job" required="required" ng-options="item.job_title for item in jobss track by item.job_id">
<option value=""> Select Job *</option>
</select>
</div>
<textarea name="msg" ng-model="msg" class="form-control textbox1" id="msg" placeholder="Write your message" required="required" rows="3"></textarea>
</div>
</div>
</div>
</div>
<center>
<button type="submit" class="btn btn-home" name="btn-save1" id="btn-save1" required="required"><i class="icon ion-email"></i> Send Message </button>
</center>
</div>
</form>
Problem is i am not able to pass dropdown value and id during form submit.
I am getting below error.
TypeError: Cannot read property 'job_title' of undefined
Please advise how can i submit the form with dropdown id and value.
Your example set a job item to the scope field "job" => ng-model="job",
the full selected item is accessible with $scope.job.
Try $scope.job.job_title or $scope.job.job_id
A print out in your html is anytime a good helper: Full job item: {{job | json}}
https://plnkr.co/edit/VenFVchI0brGZNC2Q7Fn?p=preview

Issue with nested ng-controller in Angularjs

I am stuck with strange issue. Actually I am fetching the data from ajax and showing it on text boxes.
So, basically I have 3 text box (City, City1, City2). By default City textbox is visible rest will show if they have data from Ajax.
User can add city by clicking + button or remove by click on - button.
I am able to fetch and show the data properly on textboxes.
But when I want to add/show City1 or City by clicking on + button. It is simply executing form submit event.
Here is code for Ajax call.
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_job_city.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
$scope.formData.city1 = data.city1;
$scope.formData.city = data.city;
$scope.formData.city2 = data.city2;
}
});
})
Code for form save and show hide city textboxes.
var formApp = angular.module('formApp', []);
formApp.controller('formProfile1', function($scope,$http){
$scope.secondcity1city1 = false;
$scope.thirdcity2 = false;
$scope.hidecity1 = function() { $scope.secondcity1 = false; }
$scope.hidecity2 = function() { $scope.thirdcity2 = false; }
$scope.showcity = function() { $scope.secondcity1 = true; }
$scope.showcity1 = function() { $scope.thirdcity2 = true; }
$scope.formData = {};
$scope.formprofile1 = function() {
$scope.ajaxload = true;
var allData={'formData': $scope.formData, 'uid': uid}
$http({
method : 'POST',
url : 'city_update_exec.php',
data : allData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers
})
.success(function(data) {
$scope.ajaxload = false;
if (!data.success) {
$scope.errorcity = data.errors.city;
$scope.errorcity1 = data.errors.city1;
$scope.errorcity2 = data.errors.city2;
}else{
alert('City has been updated.');
}
});
};
})
HTML codes are below.
<div class="container" ng-controller="formProfile1">
<form name="formProfile1" method="post" id="formProfile1"
ng-submit="formprofile1()" role="form">
<div ng-controller ="getprofile">
<div id="firstcity">
<div class="col-xs-10">
<div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity }">
<input name="city" id="city" type="text"
class="form-control textbox1 txt-auto"
required="required" placeholder="Job Location* "
ng-model="formData.city">
<div class = "errorba" ng-show="errorcity">{{errorcity}}
</div>
</div>
</div>
<div class="col-xs-2">
<!--<button class="remove" ng-click="removeChoice()">-</button>-->
</div>
<button class="addfields" ng-click="showcity()">+</button><br>
</div>
<div ng-show="secondcity1">
<div class="col-xs-9"><div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity1 }">
<input name="city1" id="city1" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* " ng-model="formData.city1">
<div class = "errorba" ng-show="errorcity">{{errorcity1}}
</div>
</div>
</div>
<div class="col-xs-3">
<button class="remove" ng-click="hidecity1()">-</button>
<button class="addfields" ng-click="showcity1()">+</button><br>
</div>
</div>
<div ng-show="thirdcity2">
<div class="col-xs-10"><div class="topjob_resumetitle"
ng-class="{ 'has-error' : errorcity2 }">
<input name="city2" id="city2" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* "
ng-model="formData.city2">
<div class = "errorba" ng-show="errorcity2">{{errorcity2}}
</div>
</div>
</div>
<div class="col-xs-2">
<button class="remove" ng-click="hidecity2()">-</button>
</div>
More text boxes are here
</div>
The problem is that you have not set a type for your buttons, and therefore are defaulting to submit types, which will submit the first parent form found in the DOM when clicked. To allow your custom click handlers to execute properly, change your button types to "button" like so:
<button type="button" class="addfields" ng-click="showcity()">+</button><br>
Remove method="post" and add novalidate on form tag it will stop html5 validation
<form name="formProfile1" novalidate id="formProfile1"
ng-submit="formprofile1()" role="form">
Also if its still not works then change all your button to
<input type="button">//for rest of the buttons
<input type="submit">//for submit button
To make an http request you don't need to use the separate controller. Use factory method in your code for ajax and inject it as a dependency in your controller. Refer Angular Factory method

Angular.js $cookies : not properly saved/loaded

I am trying to use a simple input that can be retrieved by a cookie automatically.
My angular controller is :
<script>
var app = angular.module('mantis', ['ngCookies']);
app.controller('main', function($scope, $cookies) {
$scope.nom = '';
$scope.WriteNom = function () {
$cookies.put('Nom', $scope.nom);
};
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
return $scope.nom;
};
});
</script>
In my page, I made a div where I can change the variable "nom" flawlessly.
The value should be loaded with ng-init (from cookie)
It changes with ng-model
And it should be saved with ng-click
<div class="container" ng-app="mantis" ng-controller="main">
<!-- Assigné à -->
<div class="col-lg-12">
<div class="input-group" ng-init="nom=ReadNom()">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="nom" type="text" class="form-control" name="nom" placeholder="Assigné à (id)" ng-model="nom">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" ng-click="WriteNom()">Sauvegarder</button>
</span>
</div>
</div>
(...)
And then, somewhere else, i can use "nom" where I need it by using {{nom}}
It's almost working :
The value is properly changed when I type in the input box and I can use it
The cookie is not changed when I click on the button nor it's loaded when I load the page
Remove the return part,
HTML:
<div class="input-group" ng-init="ReadNom()">
Controller:
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
};
DEMO

posting data through angular form without page reload in angular

$scope.createPermission= function(form){
AppFactory.createNewPermission(form)
.success(function(data) {
$scope.updatedPermissions = data;
$scope.navMode='getPermission'
var original = $scope.permission;
$scope.reset(original);
$scope.permission = {}; // clear the form
})
.error(function(data) {
console.log('Error in creating permission: ' + data);
});
$scope.Execute=function(id) {
if($scope.navMode=='updatePermission') {
$scope.editPermission(id);
} else if($scope.navMode=='createPermission') {
$scope.createPermission($scope.permission);
}
}
}
$scope.reset= function(original) {
$scope.permission= angular.copy(original)
$scope.form2.$setPristine(true);
//$scope.form2.$setUntouched(true);
}
HTML:
<div class="row">
<div class="container col-sm-6 col-sm-offset-2"
ng-show="navMode == 'createPermission' || navMode=='updatePermission' || navMode=='getPermission'">
<div>
<h1>Permissions</h1>
</div>
</div>
<form class="form2" ng-show="showHide('Create')" ng-if=""name="form2" ng-submit="Execute(permissionId)" novalidate>
<div class="form-group" ng-class="{ 'has-success': form2.name.$valid && submitted, 'has-error': form2.name.$invalid && submitted }">
<label>Permission Name</label>
<input type="text" name="name" class="form-control" ng-model="permission.name" required/>
<p class="help-block" ng-show="form2.name.$error.required && submitted">
A permission name is required
</p>
</div>
<div class="row col-lg-offset-3">
<button class="btn btn-primary" ng-disabled="form2.$invalid" type="submit">Save</button>
</div>
</form>
</div>
I have above piece of code in controller and is executed on submission of the form. Now , It does work fine on page reload but I can not add data through form back to back. I need to reload teh page everytime to post new data through the form.
Why exactly is that ?
How do I fix this?
Without seeing the HTML part of this, I would guess you are using the action attribute of <form>. AngularJS provides ng-submit which allows you to set a handler for the submit event, without actually 'submitting' the form in the traditional sense. See https://docs.angularjs.org/api/ng/directive/ngSubmit.

Error in ajax call using angular js

I am new to angular js .I tried making a small program that consists of ajax call using angular js $http .I guess I am some where wrong ,doing some mistake.
Would be happy If someone helps out. Following is code snippet
login.html
<head></head>
<body>
<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
<div ng-hide="var">
<h2><center>SIGN-IN</center></h2>
<p>Username:
<br>
<input type="text" name="user" ng-model="user" required><span style="color:red" ng-show="myForm.user.$error.required" />Username is required</p>
<p>Password:
<br>
<input type="password" name="password" ng-model="password" required /> <span style="color:red" ng-show="myForm.password.$error.required">Password is required.</span>
<p>
<input type="submit" ng-click="validate()" ng-disabled=" myForm.user.$invalid ||
myForm.password.$invalid" />
</p>
</div>
<div ng-hide="welcomeVar"> <span> {{ listOfCustomers }} </span>
<h2><center>Welcome! {{ user }}</center></h2>
<button class="list" ng-click="customerList()">List of Customers</button>
<ul>
<li ng-repeat="x in listOfCustomers">{{ x.CustomerID + ', ' + x.CompanyName }}</li>
</ul>
<br>
<button class="signout" ng-click="validate()">Log Out</button>
</div>
</form>
JS part:
<script>
function validateCtrl($scope, $http) {
$scope.user = 'ABC XYZ';
$scope.password = 'abcbc';
$scope.welcomeVar = true;
$scope.
var = false;
$scope.validate = function() {
$scope.
var = !$scope.
var;
$scope.welcomeVar = !$scope.welcomeVar
};
$scope.listOfCustomers = null;
$scope.customerList = function() {
$http.get("http://www.iNorthwind.com/Service1.svc/getAllCustomers")
.success(function(data) {
$scope.listOfCustomers = data;
})
.error(function(data) {
$scope.user = 'Xyz';
});
};
}
</script>
Your code is fine, except some syntax errors, but I hope it's because you tried to remove somrthing before posting code here ;)
Also the response for your request have this structure: {GetAllCustomersResult : [//here an array of elements]} , so, in success response handler you'll have to do: $scope.listOfCustomers = data.GetAllCustomersResult ;
But it's a minor things, the main issue described here:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
To debug this, you had to open developer tools in any browser('F12' is common key to open it), and look in console and network requests.

Resources