Angular $http.post not reaching the server - javascript

I'm having a problem getting $http.post to fire:
app.controller('editPageController', function($scope, $routeParams, $http) {
$scope.page = $routeParams.pageid;
// get page data from server
$http.get('/pages/' + $scope.page).
success(function(data, status, headers, config) {
$scope.Name = data[0].name;
$scope.Content = data[0].content;
$scope.Location = data[0].location;
}).
error(function(data, status, headers, config) {
alert("Can't get the page from the server");
});
// save page data on the server
$scope.saveEditPage = function() {
var postOBject = {Name: $scope.Name, Content: $scope.Content, Location: $scope.Location};
$http.post('/pages/' + $scope.page + '/edit', postObject).
success(function(data, status, headers, config) {
alert("success");
}).
error(function(data, status, headers, config) {
alert("Can't edit the page on the server");
});
};
});
The template code:
<script type="text/ng-template" id="editPage.html">
<h1>Edit page:</h1>
<form ng-submit="saveEditPage()">
<p>Name:</p>
<input type="text" ng-model="Name" value="{{Name}}">
<p>Content:</p>
<textarea ng-model="Content">{{Content}}</textarea>
<p>Location:</p>
<input type="text" ng-model="Location" value="{{Location}}">
<p><input type="submit" value="Save"> <input type="button" value="Cancel" ng-click="$back()"></p>
</form>
Unfortunately the $http.post does not fire. I tried wrapping the post call around $scope.$apply and it didn't work either.
How can I fix this?
Thanks
EDIT: FIXED

JavaScript variable names are case sensitive. You have declared postOBject but you are passing postObject.
ReferenceError: postObject is not defined
If I correct the typo, it's working as expected for me.
BTW I recommend using IDE with static analysis - it will inform you about undefined variables immediately. Also Firebug or Chrome DevTools javascript console are almost absolutely necessary for javascript development.

Related

Issue with populating partial view with AngularJs and MVC

I am new to AngularJs. I am using a partial view for Create and Edit operation but facing some issue wile retrieving the data.
The data is being retrieved successfully from my MVC controller but is unable to populate the view.
Here is the JS I am using
(function (angular) {
'use strict';
angular.module('Sub_Ledger_Category_Create_app', [])
.controller('Sub_Ledger_Category_Create_ctrl', function ($scope, $http, $location) {
$scope.SubLedgerCategoryModel = {};
GetRequestType();
function GetRequestType() {
$http.get('/Common/Get_Action_Request')
.success(function (result) {
//debugger;
// $scope.SubLedgerCategoryModel = data;
if (result == "Create") {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Create Sub Ledger Category </h3>");
// $("#txt_Master_Accounting_Group_Group_id").val(0);
}
else {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Edit Sub Ledger Category</h3>");
//GetEditData();
$scope.GetEditData();
}
$("#Master_Subledger_Category").val(result)
NProgress.done();
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Unable to retrieve Request Type");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.GetEditData = function () {
$http.get('/Master_Subledger_Category/GetEditData')
.success(function (data, status, headers, config) {
debugger;
$scope.SubLedgerCategoryModel = data;
console.log(data);
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Retrive Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.InsertSubledgerCategory = function () {
NProgress.start();
var Request_Type = $("#Master_Subledger_Category").val();
var Url_Master_Subledger;
if (Request_Type == "Create") {
Url_Master_Subledger = "/Master_Subledger_Category/Create_Master_Subledger_Category_Ajax";
}
else {
Url_Master_Subledger = "/Master_Subledger_Category/Test";
}
$http({
method: 'POST',
url: Url_Master_Subledger,
data: $scope.SubLedgerCategoryModel
}).success(function (data, status, headers, config) {
if (data.success === true) {
NProgress.done();
$("div.success").text("Successfully Created");
$("div.success").fadeIn(300).delay(1500).fadeOut(800);
$scope.SubLedgerCategoryModel = {};
console.log(data);
}
else {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
}
}).error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
console.log($scope.message);
});
};
})
.config(function ($locationProvider, $sceProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$sceProvider.enabled(false);
});
})(angular);
Here is the HTML:
<div class="form-horizontal" ng-app="Sub_Ledger_Category_Create_app">
<div class="box-body" ng-controller="Sub_Ledger_Category_Create_ctrl">
<div class="form-group">
<label for="txt_Master_Subledger_Category_Name" class="col-sm-2 control-label">Sub Ledger Category</label>
<div class="col-sm-10">
<input class="form-control" ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_Name" id="txt_Master_Subledger_Category_Name" name="txt_Master_Subledger_Category_Name" autofocus placeholder="Sub Ledger Category">
<input ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_ID" name="txt_Master_Subledger_Category_ID" id="txt_Master_Subledger_Category_ID" hidden />
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" value="Save" ng-click="InsertSubledgerCategory()" class="btn btn-info pull-right">Save</button>
<div class="text-red alert-box failure pull-right margin-r-5"></div>
<div class="text-green alert-box success pull-right margin-r-5"></div>
</div>
<!-- /.box-footer -->
</div>
</div>
Unfortunately I am unable to populate the view but in Console log I am able to view the data, helpful if anybody and help me.
AngularJs prevents loading HTML in this way by default. You might be getting an error on browser console: attempting to use an unsafe value in a safe context.
This is due to Angular's Strict Contextual Escaping (SCE) mode (enabled by default). Have a look to this for more information.
To resolve this issue you have 2 solutions:
$sce
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize: include the angular-sanitize.min.js resource and add the dependency in module.
hope this will help.
I have only changed the following
scope.SubLedgerCategoryModel = data;
to
scope.SubLedgerCategoryModel = data[0]:
and its resolved my issue.

failed bind angularJS variable to nodejs

i have a problem sending my angularJS POST parameters to my nodejs server... i've seen many topics related to this, tried everything here and nothing works (there were more):
How to pass parameter in Angularjs $http.post
Angular: how to pass $scope variables into the Node.js server.
How to pass client-side parameters to the server-side in Angular/Node.js/Express
How to pass data from AngularJS frontend to Nodejs backend?
my relevant code that is envolved in this problem,
handlebars-template:
<div ng-controller='questions'>
<form method="POST" class="form-inline" class="my-search-menu">
<button ng-click="search()" class="btn btn-default glyphicon glyphicon-search" type="submit" style="background-color: #85C1E9;"></button>
<input style="direction: rtl" type="text" name="search_text" ng-model="search_text" class="form-control" placeholder="Search" aria-describedby="sizing-addon3">
</form>
</div>
AngularJS:
var myapp= angular.module('myapp', []);
myapp.controller("questions", function($scope,$http) {
$scope.search = function () {
var formdata = {search_text : $scope.search_text};
$http.post('/search', {params: formdata})
.success(function (data, status, headers, config) {
$scope.questions = data;
})
.error(function(data, status, header, config){
$scope.onerror = "Data: " + status;
});
console.log(formdata);
};
});
NodeJS:
app.post('/search', function (req,res,next){
var search_text = req.query.params.formdata.search_text;
console.log(req);
Question.find({$text: {$search: search_text}}).exec(function (err, questions){
res.json(questions);
});
});
There are few points you are missing. First in the anguar controller
$http.post('/search', {params: formdata})
will send {params:formdata} as request body in the node server.. So in the server end you will receive the data as request.body. correct way to receive the body in this case will be ..
app.post('/search', function (req,res,next){
var search_text = req.body.params.search_text;
//TODO
});
If you want to send the data as parameter then in controller write the function like this...
$http({
method: 'POST',
url: '/search/'+paramData,
}).then(function successCallback(response) {
//TODO
}, function errorCallback(error) {
//TODO
});
And in the server side...
app.post('/search/:searchText', function (req,res,next){
var paramData = req.params.searchText;
//TODO
});

Angular http json request issue

Hello I have a simple question but I'm running into problems. I edited some code that I found on line. I'm trying to utilize an Angular http service to retrieve JSON data but it doesn't seem to be working
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
My code example is below
http://codepen.io/jimmyt1001/pen/dPVveN
You spelled wrong sucess should be success
CODE
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
you should use a service for this:
json.service('getJson', ['$http', function ($http) {
var promise = null;
//return service
return function () {
if (promise) {
return promise;
} else {
promise = $http.get('url');
return promise;
}
};
}]);
function MainCtrl($scope, getJson) {
getJson().success(function (data) {
$scope.json = data;
});
};
Remember to inject the service name in your controller.
tl;dr
It should be like this:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http)
{
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config)
{
$scope.posts = data;
})
.error(function(data, status, headers, config)
{
// log error
});
});
I.e. you're missing a dot (.) before success and your success is incorrectly typed (you type sucess).
Original
Your code should be structured like this:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As explained in the docs.
Yours is like this:
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
Wherea you're missing a dot (.) before the success, and your success is spelled wrong (yours is sucess).
It's decent practice to copy existing demos until you're certain on how they're really setup. Also, use your developer tools to catch easy bugs like this.
It's also possible that your dropbox call is simply invalid, but if you fix your code accordingly then the error method should be able to catch it and you should be able to see the error.

Angular - Break line text

I can't save break line text into my database, how to solve this issue?
My save data suppose to be like this
I want to ask something.
Can I?
Not like this
I want to ask something. Can I?
html
<textarea name="" cols="" rows="" class="form-control" ng-model="rule.message" required></textarea>
<button type="submit" class="btn btn-default" ng-click="create()">Save</button>
js
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + $scope.rule.message
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);
Just use the encodeURIComponent() function to encode the newlines correctly into the URL so it will be seen by the server correctly when you submit the GET request.
So your JS becomes:
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + encodeURIComponent($scope.rule.message)
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);

Pass ng-data to scope

I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});

Categories

Resources