Initialize $scope.model childs to "" or null - javascript

I'm doing this form and I'm sending the info through a $http request like this with angular
$http({
method:"POST",
url: "controllers/servicerequest.php",
data:
{
servicerequest: $scope.formData
},
headers: {'Content-Type': 'application/json'}
}).success(function(response, status, headers, config){
console.log(response);
if(response.success){
$window.open('reports/bol.php?bol='+response.id);
bootbox.alert('Service Request '+response.id+' has been processed.');
}
else{
bootbox.alert('Error message:' + response.message);
}
});
as you can see I'm sending all the data in the $scope.formData, the binding of the info works of this 2 ways
<div class="col-md-4">
<input type="text" class="form-control shipper" ng-model="formData.shipperdescripcion" name="shipper" id="shipper" ui-autocomplete="shipper">
<span class="help-block">
{{formData.shipperlocation}}
</span>
</div>
select: function(event, ui){
$scope.formData.trailerid = ui.item.id;
$scope.formData.trailerclave = ui.item.clave;
$scope.formData.trailerdueno = ui.item.propietario;
$scope.formData.trailer = ui.item.desc;
},
The thing is that I need to initialize all of the form data childs to "" when the controller loads otherwhise my the $scope.formData will be looking like this when I send the request
{}
for example, when I type something in the input the json changes from that, to this
{
"shipperdescripcion": "BUENAVENTURA AUTOPARTES S.A. DE C.V.",
}
but what I need is that before anything the controller loads the json of this way right from the start like this
{
"shipperdescripcion": "",
}

In your controller code, you can initialize the object, like the following:
$scope.model = {
shipperdescription: '', /* changing the spelling here to be correct */
id: '',
shipper: '',
shipperlocation: ''
}
A few thoughts: please consider using camelCase if possible to make your code more readable.

Related

Why is $scope not working in Angular 1.6.1?

Background
After following the AngularJS tutorial on codeSchool and reading some StackOverflow questions, I decided to start using $scope in order to avoid the hassle of having to define a var self = this; variable.
Problem
The problem is that $scope seems to not be binding anything and nothing works when I use it. I have no idea why, but if I use a var self = this; variable my code will work, even though in theory (according to what I know) $scope should do the same ...
Code
Let's say I have a page where I want to display a big list of numbers. Let's also say I have pagination, and that I want the default amount of Numbers per page to be 4. Let's also assume that after each request to the server, I set the amount of Numbers shown per page to 4 again.
app.js
/*global angular, $http*/
(function() {
var app = angular.module("myNumbers", []);
app.directive("numberFilter", function() {
return {
restrict: "E",
templateUrl: "number-filter.html",
controller: function($scope, $http) {
$scope.filter = {
itemsPerPage: 4
};
$scope.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList= response.data.entries;
$scope.totalPages = response.data.totalPages;
$scope.filter = {itemsPerPage: 4};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},
controllerAs: "filterCtrl"
};
});
})();
number-filter.html
<form ng-submit="filterCtrl.makeRequest(myNumbers.numberList)">
<div >
<label for="items_per_page-input">Items per page</label>
<input type="number" id="items_per_page-input" ng-model="filterCtrl.filter.itemsPerPage">
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
There are two expected behaviors that should happen and don't:
When I click submit, I should see in the console "Received submit order" and I don't.
The input element should be initialized with 4 when I load the page.
Both of these behaviors will happen if I use the var self = this; trick and replace all mentions of $scope with self.
Questions:
Why is this not working? Am I missing some closure?
You are using controllerAs syntax so when you use that your model needs to be assigned to the controller object itself, not to $scope
Example
controller: function($scope, $http) {
var vm = this; // always store reference of "this"
// use that reference instead of $scope
vm.filter = {
itemsPerPage: 4
};
vm.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList = response.data.entries;
vm.totalPages = response.data.totalPages;
vm.filter = {
itemsPerPage: 4
};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},

Angular js passing values from form to php [duplicate]

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
The following line needs to be added to the $http object that is passed:
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
And the data passed should be converted to a URL-encoded string:
> $.param({fkey: "key"})
'fkey=key'
So you have something like:
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
if (typeof data === "string")
return data;
for (key in data) {
if (data.hasOwnProperty(key))
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return result.join("&");
});
}]);
As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.
It can be used like this:
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
To do this only for the current post, the headers property of the request-object needs to be modified:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
You can define the behavior globally:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
So you don't have to redefine it every time:
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
These answers look like insane overkill, sometimes, simple is just better:
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
You can try with below solution
$http({
method: 'POST',
url: url-post,
data: data-post-object-json,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var key in obj) {
if (obj[key] instanceof Array) {
for(var idx in obj[key]){
var subObj = obj[key][idx];
for(var subKey in subObj){
str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
}
}
}
else {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
}
return str.join("&");
}
}).success(function(response) {
/* Do something */
});
Create an adapter service for post:
services.service('Http', function ($http) {
var self = this
this.post = function (url, data) {
return $http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
}
})
Use it in your controllers or whatever:
ctrls.controller('PersonCtrl', function (Http /* our service */) {
var self = this
self.user = {name: "Ozgur", eMail: null}
self.register = function () {
Http.post('/user/register', self.user).then(function (r) {
//response
console.log(r)
})
}
})
There is a really nice tutorial that goes over this and other related stuff - Submitting AJAX Forms: The AngularJS Way.
Basically, you need to set the header of the POST request to indicate that you are sending form data as a URL encoded string, and set the data to be sent the same format
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // 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)
});
Note that jQuery's param() helper function is used here for serialising the data into a string, but you can do this manually as well if not using jQuery.
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Please checkout!
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
For Symfony2 users:
If you don't want to change anything in your javascript for this to work you can do these modifications in you symfony app:
Create a class that extends Symfony\Component\HttpFoundation\Request class:
<?php
namespace Acme\Test\MyRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class MyRequest extends Request{
/**
* Override and extend the createFromGlobals function.
*
*
*
* #return Request A new request
*
* #api
*/
public static function createFromGlobals()
{
// Get what we would get from the parent
$request = parent::createFromGlobals();
// Add the handling for 'application/json' content type.
if(0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/json')){
// The json is in the content
$cont = $request->getContent();
$json = json_decode($cont);
// ParameterBag must be an Array.
if(is_object($json)) {
$json = (array) $json;
}
$request->request = new ParameterBag($json);
}
return $request;
}
}
Now use you class in app_dev.php (or any index file that you use)
// web/app_dev.php
$kernel = new AppKernel('dev', true);
// $kernel->loadClassCache();
$request = ForumBundleRequest::createFromGlobals();
// use your class instead
// $request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Just set Content-Type is not enough, url encode form data before send.
$http.post(url, jQuery.param(data))
I'm currently using the following solution I found in the AngularJS google group.
$http
.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.data = data;
});
Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals() to read this, as $_POST won't automatically loaded with it.
AngularJS is doing it right as it doing the following content-type inside the http-request header:
Content-Type: application/json
If you are going with php like me, or even with Symfony2 you can simply extend your server compatibility for the json standard like described here: http://silex.sensiolabs.org/doc/cookbook/json_request_body.html
The Symfony2 way (e.g. inside your DefaultController):
$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());
The advantage would be, that you dont need to use jQuery param and you could use AngularJS its native way of doing such requests.
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
In your app config -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
With your resource request -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
This isn't a direct answer, but rather a slightly different design direction:
Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable
Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:
http://www.someexample.com/xsrf/{xsrfKey}
Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL
Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field
{
appointmentId : 23,
name : 'Joe Citizen',
xsrf : '...'
}
You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.
In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.
Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.
How do you post array in a form payload? Maybe like this:
shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday
or this:
shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday
Both are poor design..
This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data
var deferred = $q.defer();
$http({
method: 'POST',
url: apiserver + '/authenticate',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: userData
}).success(function (response) {
//logics
deferred.resolve(response);
}).error(function (err, status) {
deferred.reject(err);
});
This how my Userdata is
var userData = {
grant_type: 'password',
username: loginData.userName,
password: loginData.password
}
The only thin you have to change is to use property "params" rather than "data" when you create your $http object:
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Use AngularJS $http service and use its post method or configure $http function.

POST form data using AngularJS

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'}
});

AngularJS 1.2.0 $resource PUT/POST/DELETE do not send whole object

I'm using angularjs 1.2.0 with $resource. I would like to have some PUT/POST instance actions that doesn't send the whole object to the server but only some fields and in some cases totally no data.
Is it possible? I searched everywhere but couldn't find anything
UPDATE:
It also happens with DELETE requests:
Given this code:
group.$deleteChatMessage({messageId: message.id}, function(){
var i = _.indexOf(group.chat, message);
if(i !== -1) group.chat.splice(i, 1);
});
The request is this:
See how the whole model is sent (under "Request Payload").
This is the resource:
var Group = $resource(API_URL + '/api/v1/groups/:gid',
{gid:'#_id', messageId: '#_messageId'},
{
deleteChatMessage: {method: "DELETE", url: API_URL + '/api/v1/groups/:gid/chat/:messageId'},
});
This works for me:
$resource(SERVER_URL + 'profile.json',
{},
{
changePassword :
{
method : 'POST',
url : SERVER_URL + 'profile/changePassword.json',
// Don't sent request body
transformRequest : function(data, headersGetter)
{
return '';
}
}
});
You could customise exaclty what is sent to the server by implementing your own code in the transformRequest function. In my example I was adding a new function to the REST client, but you can also overwrite existing functions. Note that 'transformRequest' is only available in version 1.1+
You can use $http for that specifically. However, I have one case I use for a project that might help. Also my example is returning an array from the server but you can change that.
In my service:
app.factory('mySearch', ['$resource', function($resource) {
return $resource('/api/items/:action', {}, {
search: { method: 'POST', isArray: true,
params: { action: 'search' }
}
});
}
]);
In my Controller:
I can build up custom params to post to server or if its only two fields I need from a table row the user selects.
var one = "field_one";
var two = "field_two";
$scope.search({one: one, two: two});
Then I can post those through an event and pass the custom params
$scope.search = function(customParams) {
mySearch.search({query: customParams}, function(data) {
$scope.items = data;
}, function(response) {
console.log("Error: " + response.status);
})
};
Hopefully this was some help. Let me know if this is close to what your looking for and I can help more.
POST
DELETE

Get selected options and pass it using $http in Angularjs?

I am trying to pass the selected option value calling on the function on change.
<div class="col-md-4">
<select id="mkSelect" ng-model="formData.mk" name="mkSelect" ng-options="mk.MkIdLabel group by mk.FY for mk in mks" ng-change="update()" class="form-control">
</select>
</div>
And in the controller:
$scope.update = function() {
// this displays the MarketId value in the log
console.log($scope.formData.mk.MarketId);
$http({
method: 'POST',
url: 'getMailStatus.php',
// but while trying to send to "getMailStatus.php" it says its undefined
data: $.param($scope.formData.mk.MarketId),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
The console.log displays the selected id , but when I try to pass the same using $http it says undefined ($scope.formData.market.MarketID = undefined)
Can anybody point me what i am doing wrong?
$.param needs an object, not a simple value.
http://api.jquery.com/jquery.param/
Try with this:
data: $.param({mkId: $scope.formData.mk.MarketId}),

Categories

Resources