I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})
Related
I am stuck, where is the memory leakages?
What I am trying?
After import the .xlsx (store) I am fetching them again in the response (I also try to fetch them independently on other ele click event ).
Problem:
After uploading 2 -3 files chrome browser freeze on $http.post(...) ( Working fine in FF), I have added code sample.
Thanks!
/***** HTML *****
<input type="file" onchange="angular.element(this).scope().storeBulkUpdate(this)">
*****/
/*** Controller */
var paginationCriteria = {
pageNo: 1,
size: 10
};
$scope.getAllStoreStores = function (_data, qParam) {
storeSevice.getStore(_data, $httpParamSerializer(qParam)).success(function (data) {
console.log(data)
});
}
$scope.storeBulkUpdate = function (element) {
var fileData = element.files[0];
var formData = new FormData();
formData.append('file', fileData);
storeSevice.bulkUpdateStore(formData).success(function (data, status, headers, config) {
$scope.getAllStore({}, paginationCriteria);
});
};
/**Factory 'storeSevice' */
return {
bulkUpdateStore: function (_postData) {
url = '/upload'
//Set Headers
var header = {};
var extendedHeader = AuthenticationService.createAuthorizationHeader(
header,
url,
'POST',
_postData
);
extendedHeader['ServiceName'] = 'uploadMTTForStore';
extendedHeader['Content-Type'] = undefined;
//Headers End
return $http.post(url, _postData, {
withCredentials: false,
headers: extendedHeader,
transformRequest: angular.identity
});
},
getStore: function (_postData, $parameters) {
url = '/getStore?' + $parameters;
var header = {};
var extendedHeader = AuthenticationService.createAuthorizationHeader(
header,
url,
'POST'
);
extendedHeader['ServiceName'] = 'storeFetch';
//browser feerze
return $http.post(url, $postData, {
headers: extendedHeader
});
},
otherMethods: "etc......."
}
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -
Error: $injector:modulerr
Module Error
Then I tried searching for the why the module won't load but with no luck.
main.js /*File where app module is declared*/
var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
I tried injecting the dependency for the controller files.
Controllers:
Link Controller
var app = angular.module('app');
app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*First AJAX request which gets all the links and categories for the user*/
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
$scope.getUser = function () {
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
};
$http({
method: 'GET',
url: '/links'
}).then(function successCallback(response) {
this.orderProp = 'age';
/*the response is saved in scope variables*/
$scope.links = response.data[0];
$scope.categories = response.data[1];
$scope.categorytolink = response.data[2];
}, function errorCallback(response) {
console.log('There was a problem! Refresh!');
});
/*AJAX request for getting the recommendations according to the most viewed stars*/
$http({
method: 'GET',
url: '/recommendations/top'
}).then(function successCallback(response) {
$scope.recommendations = response.data;
}, function errorCallback(response) {
});
/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
$http({
method: 'GET',
url: "/proxy",
headers: {
"X-Proxy-To": link.rss_link
}
}).then(function successCallback(response) {
/*AJAX request: add a star to the link*/
$http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {
// Manually increment star for link just clicked
var $data;
$data = data.data;
$scope.link = $data;
console.log('200 OK! Star added');
}, function errorCallback() {
console.log('Error!');
});
/*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/
$myXml = response.data;
$xmlObj = $.parseXML($myXml);
$newsItems = [];
$channelImage = $($xmlObj).find("channel>image");
/*the information of the link is sorted */
$linkData = {
"title": $channelImage.find("title").text(),
"link": $channelImage.find("link").text(),
"imgurl": $channelImage.find("url").text()
};
/*the data is sorted below*/
$.each($($xmlObj).find("item"), function (index, value) {
$newsItems.push({
"title": $(value).find("title").text(),
"description": $(value).find("description").text(),
"link": $(value).find("link").text(),
"date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
"time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
"guid": $(value).find("guid").text()
})
});
$scope.newsItems = $newsItems;
$scope.linkData = $linkData;
}, function errorCallback(response) {
});
};
/*Create a category private to the user*/
$scope.create_category = function (category) {
/*AJAX request: adds a new category*/
$http.post('/categories/new', {'category': category}).then(function successCallback(response) {
/*AJAX request: Updates the categories for the use of new category*/
$http({
method: 'GET',
url: '/categories'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
});
}, function errorCallback(response) {
});
};
}]);
User Controller
var app = angular.module('app');
app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.dzOptions = {
paramName: "file",
dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
createImageThumbnails: false,
autoDiscover: false
};
$scope.dzCallbacks = {
'sending': function (file, xhr, formData) {
formData.append('_token', $('#csrf-token').val());
},
'success': function (file, response) {
$scope.user = response;
$.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
}
};
/*Update user info*/
$scope.updateUser = function () {
/*AJAX request: update user info*/
$http.post('/users/update', {
'name': $scope.user.name,
'username': $scope.user.username,
'email': $scope.user.email
}).then(
function successCallback(data) {
$scope.user = data;
$.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
console.log('200 OK! User updated');
}, function errorCallback() {
console.log('Error!');
});
};
}]);
Article Controller
var app = angular.module('app');
app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*Populates the comments for particular
* */
$scope.populatecomments = function (newsItem) {
$http({
method: 'GET',
url: '/articles/' + newsItem.guid + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
});
};
$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
if ($scope.txtcomment != '') {
$scope.data.push({
"comment": $scope.txtcomment,
"guid": newsItem.guid
});
$http.post('/comments/new', {
"comment": $scope.txtcomment,
"guid": newsItem.guid
}).then(function successCallback() {
var encodedURI = encodeURIComponent(newsItem.guid);
$http({
method: 'GET',
url: '/articles/' + encodedURI + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
$scope.txtcomment = "";
}, function errorCallback(response) {
});
}, function errorCallback() {
console.log('Error comment!');
});
}
};
$scope.savearticle = function (newsItem) {
$http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
/*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
}, function errorCallback(response) {
});
}
/**
* The saved articles by the user will be retrieved when a button clicked
*/
$scope.getSavedArticles = function () {
/*AJAX request: retreive the saved the saved articles for the user*/
$http({
method: 'GET',
url: '/saved-articles'
}).then(function successCallback(response) {
$scope.linkData = null;
$scope.newsItems = response.data;
}, function errorCallback(response) {
});
};
}]);
HELP needed!
Yo do not need to declare module in each controller file. Remove the line in each controller
var app = angular.module('app');
You are injecting controller in you module like dependency.
Change your main.js file to this:
var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
#Sajeetharan is right you do not need module declaration in all controllers.
Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )
There are two ways to do this:
Change the Angular Tags
var app = angular.module('app', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
Now Laravel will use the {{ variableName }} and Angular will use <%
variableName %>.
Change the Laravel Blade Tags
Blade::setContentTags('<%', '%>');// for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
Variables will be: <% $variable %>. Comments will be: <%-- $variable
--%>. Escaped data will look like: <%% $variable %%>.
You can check this Tutorial for more info.
Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});
'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.
Both registerUser and login call fails because of 'Undefined' character:
Request URL: http://localhost:25971/undefined/api/Account/Register
Request URL: http://localhost:25971/undefined/Token
Here is my code:
(function () {
"use strict";
angular
.module("userManagement")
.controller("mainCtrl", ["userAccount", mainCtrl])
function mainCtrl(userAccount) {
var vm = this;
vm.isLoggedIn = false;
vm.message = '';
vm.userData = {
userName: '',
email: '',
password: '',
confirmPassword: ''
};
vm.registerUser = function () {
vm.userData.confirmPassword = vm.userData.password;
userAccount.registration.registerUser(vm.userData, function (data) {
vm.confirmPassword = "";
vm.message = "...Registration successful";
// vm.login();
});
}
vm.login = function () {
vm.userData.grant_type = "password";
vm.userData.userName = vm.userData.email;
userAccount.login.loginUser(vm.userData, function (data) {
vm.isLoggedIn = true;
vm.password = "";
vm.message = "";
vm.token = data.access_token;
});
}
}
}());
Here is the code in userAccount factory method:
(function () {
"use strict";
angular.module("common.services")
.factory("userAccount", ["$resource", "appsettings", userAccount])
function userAccount($resource, appsettings) {
return {
registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
{
'registerUser': { method: 'POST' }
}),
login: $resource(appsettings.serverPath + "/Token", null,
{
'loginUser': {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (data, headersGetter) {
var str = [];
for (var d in data) {
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&")
}
}
}
})
}
}
})();
Appsettings is defined like this:
(function () {
"use strict";
angular.module("common.services", ["ngResource"]).constant("appsettings", {
serverpath:"http://localhost:25879/"
});
}());
I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!
You appsettings constant should look like:
(function (angular) {
"use strict";
angular.module("common.services", ["ngResource"]).constant("appsettings", {
serverPath: "http://localhost:25879"
});
}(angular));
The property serverpath is not the same as serverPath and in you case serverPath is undefined. You should respect the casing.
Check for serverPath in apiSettings
hi im new in vertx and i want use https://github.com/vert-x/mod-mysql-postgresql for a service
i use this code for my web server
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13} i want insert this in any table in postgre
//do
var dataresponse= messagefrompostgre;//e: {status:"ok", code:200, message: "its ok"}
req.response.putHeader("Content-Type", "application/json");
req.response.end(dataresponse);
});
}
and this is my event click button
$.ajax({
data: {name:foo, age:13} ,
url: '/foo',
type: 'post',
dataType: 'json',
complete: function (response) {
alert(JSON.stringify(response));
}
});
I found how to do it:
var vertx = require('vertx');
var console = require('vertx/console');//TODO: remove
var eventBus = vertx.eventBus;
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
var jsona={
"action" : "raw",
"command" : "select * from test"
}
eventBus.send("PostgreSQL-asyncdb",jsona, function(reply) {
req.response.putHeader("Content-Type", "application/json");
req.response.end(JSON.stringify(reply));
});
});
}
and this return:
{"message":"SELECT 6","rows":6,"fields":["testt"],"results":[["lol"],["lolŕ"],["lol2"],["lol2"],["testlol"],["testlolp"]],"status":"ok"}