I am having trouble sending URL parameters to a rest method through a angular optimized html page.
My rest method:
router.get("/url/id/:urlid",function(req,res){
var query = "SELECT urlID AS libraryid, "
+ "URL AS libraryitem "
+ "FROM ?? "
+ "WHERE active = 1 "
+ "AND ?? = ? "
whereClause = ['urls', 'urlid', req.params.urlid];
query = mysql.format(query,whereClause);
connection.query(query,function(err,rows){
if(err) {
console.log("Rest Call Error");
res.json({"Error" : true, "Message" : "Error executing MySQL query", "Query" : query});
} else {
console.log("Rest Call Success", rows);
res.json({"Error" : false, "Message" : "Displayed the url "+req.params.urlid, "Query" : query, "URLs" : rows});
}
});
I can call the rest method directly and receive the following results
{
"Error": false,
"Message": "Displayed the url 5",
"Query": "SELECT urlID AS libraryid, URL AS libraryitem FROM `urls` WHERE active = 1 AND `urlid` = '5' ",
"URLs": [
{
"libraryid": 5,
"libraryitem": "url"
}
]
}
The Controller
app.controller("UrlByIDController", function ($scope, $http) {
$http.get('/api/url/id/{{urlid}}')
.then(function(data) {
console.log("URl loading", data)
$scope.links = data['URLs'];
})
.catch(function(response) {
console.error('Loading URL error', response.status, response.data);
})
.finally(function() {
console.log("finally finished loading urls");
});
});
The html template
<div class="form-group">
<label for="txtURL" class="control-label col-xs-3">URL</label>
<div class="col-xs-3" ng-controller="UrlByIDController" >
<input type="text"
id="txtURL"
class="ng-valid ng-dirty"
ng-model="formData.txtURL"
value="{{links.libraryitem}}"
placeholder="URL of Ad" />
</div>
</div>
When I debug the page I don't get an error but the id value that is passed to the rest method is the phrase 'urlid'. I am sure it is something pretty basic I am missing.
You cannot access your urlid in your Angular Controller with "{{urlid}}". This syntax can only be used in your HTML Template.
I can't see in your Controller how you get your urlid value from. One possibility would be to access urlid in $scope. But you have to set it somewhere first:
$http.get('/api/url/id/' + $scope.urlid)
Related
HTML CODE
<h1 class="popup-title full-width no-margin padding-right source-border-bottom"><span>Enter Employee ID</span></h1>
<div class="bar bar-subheader has-header-text no-border search-txt modal-side-align-search">
<label class="item item-input no-padding no-border asda-txtbox-border search-label txt-box-border">
<input type="search" resizepopup class="txt-box search-txtbox" placeholder="Search with keyword..." ng-model="employeeCode" ng-change="scrolltoTop()" ng-blur="fieldBlur()" id="searchSource" ng-keypress="searchEmployee($event)">
<!--<i class="icon ion-search search-icon"></i> -->
<img class="searchStyle" src="assets/images/search.png">
</label>
</div>
JS CODE
$scope.employeeCode = "";
var dataForService = {
"authToken": "",
empCode: ""
}
$scope.searchEmployee = function(keyEvent){
if (keyEvent.which === 13)
{
console.log("The employee code is "+$scope.employeeCode);
UtilityFactory.showLoading();
dataForService.authToken = authTok; // authTok is generated in another part of the program
dataForService.empCode = $scope.employeeCode;
console.log(JSON.stringify(dataForService));
Factory.webCallEmployee(dataForService).success(function(data, status, headers, config) {
var response = data;
console.log(JSON.stringify(response));
console.log(response.employee.employeeCode);
if (response.responseStatus === "success") {
$timeout(function() {
UtilityFactory.hideLoading();
}, 2000);
}
else{
UtilityFactory.hideLoading();
console.log('This employee is not present in our records');
$ionicPopup.alert({
title: 'Error',
template: 'This employee is not present in our records'
}).then(function(res) {
console.log('Error in else block');
});
}
}).error(function(data, status, headers, config) {
alert(status);
UtilityFactory.hideLoading();
$ionicPopup.alert({
title: 'Error',
template: 'Error statement'
});
});
}
}
JSON DATA
{
"responseStatus":"success",
"employee":{
"employeeCode":"E001",
"employeeName":"ABC",
"employeeMobileNo":"1234567890",
"comCode":"0000029558",
"comName":"Digital Mirror",
"deptCode":"HR"
}
}
I have a factory , from which I am getting the correct response status , for learning sake I am using hard-coded JSON data instead of real service but I have one issue -
In my JSON data the only hardcoded employee no is E001 , but I enter any other value it should go to the error block & give me an error , it is always entering the success block , I mean to say if the employee is not E001 , if i enter say Tom as Employee No , it should go the error block but it is not happening
Also if the employee is present I want to display this employee is present , other "Sorry this employee is not available"
Please refer the image to find what I am to do
I don't get any error message, but while debugging Scope values are not binding it shows Undefined...
Controller:
$scope.companyModify = function () {
var param = {
companyId:$scope.companyId,
companyName:$scope.companyName,
billPrintLinesTop:$scope.billPrintLinesTop,
billPrintLinesBottom:$scope.billPrintLinesBottom,
isPrintHeader:$scope.isprintHeader,
billTypeId:$scope.billTypeId,
billColumnId :$scope.billColumnId,
noOfCopies: $scope.noOfCopies,
billHeaderAlignmentId: $scope.billHeaderAlignmentId,
billTitle: $scope.billTitle,
billSortOrderId:$scope.billSortOrderId,
posDefaultQty:$scope.posDefaultQty,
posTaxTypeId:$scope.posTaxTypeId,
isAllowNegativeStock:$scope.isAllowNegativeStock,
serviceTaxCalcTypeId : $scope.serviceTaxCalcTypeId,
wishMessage:$scope.wishMessage,
coinageBy:$scope.coinageBy,
isAutoGenerateProductCode:$scope.isAutoGenerateProductCode
};
console.log(param);
Calling the companyModify Function :
Open braces of companyModify closes in SocketService...
SocketService.post(apiManage.apiList['CompanyModify'].api,param).
then(function (resp) {
var data = resp.data.response;
if (data.status === true) {
angular.forEach($scope.companyList, function (value) {
if (value.companyId == $scope.companyId) {
value.$edit = false;
}
});
Notify.alert(data.message, {
status: 'success',
pos: 'top-right',
timeout: 5000
});
$scope.load();
}
else {
Notify.alert(data.message, {
status: 'danger',
pos: 'top-right',
timeout: 5000
});
}
});
};
Ensure $scope is properly injected in controller
someModule.controller('MyController', ['$scope', function($scope) {
...
$scope.aMethod = function() {
...
}
...
}]);
In your html code, input values are binded to company.XXX :
<input type="text" class="form-control input-sm" ng-model="company.posTaxTypeId" placeholder="Enter POSTaxCalculation" >
If you want your code to work is the controller, you must use the same binding and use posTaxTypeId: $scope.company.posTaxTypeId instead of posTaxTypeId: $scope.posTaxTypeId
or change your html code to :
<span data-ng-show="!company.isEdit" data-ng-bind="posTaxTypeId"></span>
<span data-ng-show="company.isEdit">
<input type="text" class="form-control input-sm" ng-model="posTaxTypeId" placeholder="Enter POSTaxCalculation" >
</span>
also ensure that binding are declared properly, without spaces :
bad
data-ng-bind="company.posTaxTypeId "
ng-model="company.posTaxTypeId "
good
data-ng-bind="company.posTaxTypeId"
ng-model="company.posTaxTypeId"
I have a website where a user stores resources and makes articles about them. At this time, i'm building the comments section where users can make comments in the articles. I have a put request which is triggered from controller which sends the id of the article and the comment.
but i receive the following error,
SyntaxError: Unexpected token 1
at parse (/home/themis/webappionio/node_modules/body-parser/lib/types/json.js:83:15)
at /home/themis/webappionio/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/home/themis/webappionio/node_modules/raw-body/index.js:262:16)
at done (/home/themis/webappionio/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/home/themis/webappionio/node_modules/raw-body/index.js:308:7)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at doNTCallback2 (node.js:441:9)
at process._tickCallback (node.js:355:17)
here is my server.js:
//defining Articles Model
var ArticleSchema = mongoose.Schema({
_creatorname: String,
title : String,
body : String,
resource: String,
published : String,
comments: [{
_commentorname: String,
content : String,
date : String
}]
});
var Articles = mongoose.model("Articles", ArticleSchema);
//pushing comment into the specific article
app.put("/home/:id", function(req,res){
var _commentorname = req.user.username;
var content = req.body.comment;
var date = moment().tz("Europe/Athens").format("DD/MM/YY HH:mm");
Articles.findByIdAndUpdate(
id,
{$push: {"comments" : {_commentorname: _commentorname, content: content, date: date}}},
{safe: true, upsert: true, new : true},
function(err, article) {
console.log(err);
}
);
});
My controller :
$scope.addComment = function(id, comment) {
console.log(id);
console.log(comment);
$http.put("/home/" + id, comment)
.success(function(response){
$scope.all();
});
};
and my html form:
<div class="panel-footer">
<input type="text" id="userComment" ng-model="comment" class="form-control input-sm chat-input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" ng-click="addComment(article._id, comment)"><span class="glyphicon glyphicon-comment"></span> Add Comment</button>
</span>
</div>
Here is my final server.js
app.put("/home/:id", function(req,res){
var id = req.params.id;
Articles.findByIdAndUpdate(
id,
{$push: {"comments" : {_commentorname: req.user.username, content:req.body.comment}}},
{safe: true, upsert: true, new : true},
function (err, results) {
if (err)
{
res.send("there was a problem updating the information: " + err);
}
else {
res.format({
json: function() {
res.json(results);
}
});
}
}
);
});
The problem is that comment here is not actually being sent as an Object but just as a "string". So you need to structure the Object instead.
So correct the angular controller code:
$scope.addComment = function(id, comment) {
console.log(id);
console.log(comment);
$http.put("/home/" + id, { "comment": comment})
.success(function(response){
$scope.all();
});
};
New Answer:
Actually it looks like that you are submitting in the Angular controller the comment variable in a "raw" way instead of sending it as JSON, you need to change it to the
$scope.addComment = function(id, comment) {
console.log(id);
console.log(comment);
$http.put("/home/" + id, {comment: comment})
.success(function(response){
$scope.all();
});
};
Old Answer:
I think it throws the error because you format the date to the unusual format "DD/MM/YY HH:mm", if you would use native JS object it would work, e.g.
var date = moment().tz("Europe/Athens").toDate()
I'm currently building a comment system and would like to include the ability to mention users and tag them, subsequently I would like the tag to have a link to their profile (In this example, it's just /profile/{id})
I am currently using Laravel Mentions to generate the auto filled list from my Users Model. I'm doing it like:
function enableMentions(elem, type, column) {
$(elem).atwho({
at: "#",
limit: 5,
displayTpl: '<li><span>${name}</span></li>',
insertTpl: '${name}',
callbacks: {
remoteFilter: function(query, callback) {
if (query.length <= 1) return;
$.getJSON("/api/mentions/" + type, {
q: query,
c: column
}, function(data) {
callback(data);
});
}
}
});
}
// My api/mentions route: Route::get('/api/mentions/{type}', 'ApiController#index');
//My api controller:
public function index($type, Request $request)
{
try {
$resultColumns = [];
$query = $request->get('q');
$column = $request->get('c');
$model = app()->make(config('mentions.' . $type));
$records = $model->where($column, 'LIKE', "%$query%")
->get();
foreach ($records as $record) {
$resultColumns[] = $record->$column;
}
return response()->json($resultColumns);
} catch (\ReflectionException $e) {
return response()->json('Not Found', 404);
}
}
And finally, initializing the at.js
<script type="text/javascript">
$(function(){
enableMentions("#mention-commentContent", "users", "Username");
});
</script>
<div contentEditable="true" id="mention-commentContent" class="user-form" name="commentContent" type="text"></div>
I'm confused on how I can modify the above to return the username and the ID assigned to them, that way I can change the ${name} to ${id} and have it link through to their profile, right?
This package may help Laravel Mentions or this .
The basic idea is getting the usernames from the database via JSON , here is how they are using it in laracasts:
$("textarea#body").atwho({
at: "#", limit: 5, callbacks: {
remoteFilter: function (t, e) {
t.length <= 2 || $.getJSON("/api/users", {q: t}, function (t) {
e(t)
})
}
}
})
How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?
Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.
My controller code:
`app.controller('SearchController',['$scope','$http',function($scope,$http){
$scope.click=function(){
var data=$scope.query1;
$http.post('/credjson',data);
/*$scope.addRowAsyncAsJSON = function(){
$scope.cred.push({ 'query':$scope.query1 });
var dataObj = {
query : $scope.query1,
};
var res = $http.post('/credjson', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
$scope.query1='';*/`
Note: The code in between /* */ was a different attempt at trying this out.
My view code:
`<div style="padding-top:20px" ng-controller="SearchController">
<form name="form1" ng-submit="click()">
<input id="creditq" ng-model='query1' type="text" />
<button id="Search" ng-value='Search'>Search</button><br/><br/>
</form>
</div>`
Just construct your JSON payload and pass it to $http as the second param
data: { query1: $scope.query1 }
and then
$http.post('/credjson',data);