Internal column name reference not working in Sharepoint - javascript

I tried to retrieve a lookup column from a list. The list name is "Colors" and the lookup column name is "RedPencilBox:E-Mail"; however, I am getting the "error in controller 2" alert. I wonder if this is because of the length of the internal name of "RedPencilBox:E-Mail"(?).
var module2 = angular.module('App2', []);
module2.controller('Controller2', function ($scope, $http) {
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Colors')/items?$select=Title, Id, RedPencilBox%5Fx003A%5FE%5Fx002d%5FMail/EMail&$expand=RedPencilBox%5Fx003A%5FE%5Fx002d%5FMail/EMail",
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.project = data.d.results;
}).error(function (data, status, headers, config) {
alert("error in Controller2");
});
});

Try your request url right in a browser. It should return an exact error, maybe you'll get a clue.
Also try this url without query parameters: "webURL + /_api/web/lists/getByTitle('Colors')/items" - to see if your field's internal name is exactly the same you have in the query url.
I don't think you need encoding here: just try pass it as it is: RedPencilBox_x003A_E_x002d_Mail
Best regards, Polina

Related

Angularjs $http.post - sending params as JSON to ASPX webmethod

I have the following angularjs code sending http post to a webmethod, but I get the following error with no more info. Can someone help?
If I do not send any data to webmethod and only get data from it, it works just fine !
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
angular.js:11442 POST http://localhost:54461/GetData.aspx/getData 500 (Internal Server Error)
Javascript:
var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
$scope.retData = {};
var config = {
headers: {
'Content-Type': '"application/json; charset=utf-8";',
'dataType': '"json"'
}
}
$scope.retData.getResult = function (item, event) {
$http.post('GetData.aspx/getData', request, config)
.success(function (data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
ASPX webmethod (C#):
public static string getData(string name, int age)
{
string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}
EDIT --------------------------------------
If I do not send any json data to the webmethod, it works just fine. for example the below code works and if I put break point inside the webmethod, it shows that it goes there. but if I send json data, it does not go inside webmethod:
Javaacript (not sending any json data):
var config = {
headers: {
'Content-Type': '"application/json; charset=utf-8";',
'dataType': '"json"'
}
}
$scope.retData.getResult = function(item, event) {
$http.post('GetData.aspx/getData', data, config)
.success(function(data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});
}
ASPX (When no input param)
public static string getData()
{
// just having a breakpoint shows it comes inside the
// webmethod when no data is passed.
}
your issue seems to be as pointed by Emmanual Durai in first comment of your question: var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}"; is not a valid json object.
request will give you {'name':'Nariman'age':'12'} as String which won't parse to JSON (there are issues with format).
You should try something like below to get a valid string
var request = {
name: "Nariman",
age: 12
}
var requestString = JSON.stringify(request)
also please have a look here How to pass json POST data to Web API method as object. your issue is not typically specific to angularjs $http but in general to XHR request.
Simply change:
var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
To:
var request = { name: "Nariman", age: 12 };
You don't have to use JSON.stringify()
var request = { name: "Nariman", age: 12 };
var config = {
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}
$http.post('GetData.aspx/getData', request, config)
.success(function(data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});

malformed JSON string Error while passing JSON from AngularJS

I am trying to pass JSON string in ajax request. This is my code.
NewOrder = JSON.stringify (NewOrder);
alert (NewOrder);
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: "mydata="+ NewOrder
};
$http(req)
.success(function (data, status, headers, config) {
alert ('success');
})
.error(function (data, status, headers, config) {
alert (status);
alert (data);
alert ('Error')
});
alert (NewOrder) gives -
{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}
Which seems to be a valid JSON string.
But in script side I am getting following error. in this line
my $decdata = decode_json($cgi->param('mydata'));
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")
Can please someone help me why i am getting this error?
$cgi->param('myData') returns the query param string 'mydata', which in your case is not sent.
You're posting the json data in the request body of your http post payload, and not as a query/form param. In that case, you'd need some other function to read the contents of the request body in your server-side script.
which happens to be:
my $data = $query->param('POSTDATA');
as described in here: http://search.cpan.org/~lds/CGI.pm-3.43/CGI.pm#HANDLING_NON-URLENCODED_ARGUMENTS
Also you should remove the "mydata=" from your json in the body you post, because http request payload bodies do not have parameter names (they're for query/form-params only).
Your end code should be like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: NewOrder
};
and the servers side:
my $decdata = decode_json($query->param('POSTDATA'));
I think it may be related to this issue: AngularJs $http.post() does not send data
Usually I would post data like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: {"mydata" : NewOrder}
};
However I am assuming that you are expecting the data as request params from this:
my $decdata = decode_json($cgi->param('mydata'));
If that is the case then the linked SO question is what you are looking for.
Angular $http.post accepts two params as url and payload
var url = '/cgi-bin/PlaceOrder.pl';
var payLoad = {'myData' :JSON.stringify(NewOrder)};
$http.post(url, payLoad)
.success(function(data) {
console.log(success);
})
At the server side, while fetching the required json string from the request param and then desearlize the json as following:
$result = $cgi->param('myData');
my $decdata = decode_json($result);

cordova + angularjs + nodejs(Express) $http json always get 404

I am using cordova + angularjs + nodejs(Express) to test in android environment. Now I am trying to get some data by $http(), but I always get 404 error (by the alert below).
Client Code ( AngularJs )
$http({
method : 'POST',
url : "http://192.168.1.4:8888/login",
data : ""
})
.success(function(data, status, headers, config) {
alert("success");
alert(data);
})
.error(function(data, status, headers, config) {
alert("error");// <== always gets here
alert(status); // <== 404
}).
finally(function() {
alert("finally");
});
Server Code (NodeJs+Express)
...
app.get('/login',function(req, res){
res.set({'Content-Type':'application/json','Encodeing':'utf8'});
res.json({name:"jj"});
}) ;
app.listen(8888);
I can get the json string by visit http://192.168.1.4:8888/login by Chrome,
I searched a lot of stuff but still can't solve my problem, could anyone help?
The http method is post, it needs to be get.

Angular js http.get request not hitting my url

as i am working on angular js for using the rest-full web services in my website,
but my problem is i am getting controll into error field instead of success and i stucked into it since past three days any help will be appreciated more, and this is my anguls js code.
`
function customersController1($scope, $http) {
$http({
url: 'http://localhost:9090/quote',
dataType: 'text/json',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function(data){
$scope.data = data;
alert(data);
}).error(function(error){
$scope.error = error;
alert('error');
});
}
</script>
`enter code here`<div ng-controller="customersController1">
<!-- div>{{ quotes }}</div-->
<ul>
cc <li ng-repeat="quotes"> cc{{ quotes }}</li>
</ul>
</div>`
thanks in advance friends.
First make sure the url is working by accessing it in browser and then ensure sure you are using ng-app in your html .
Next -
$http's config object doesn't have ant property 'dataType'. you can remove and try your example.
$http(
{
method : 'GET',
url : 'http://localhost:9090/quote',
}
).success( function(data, status, headers, config)
{
})
.error(function(data, status, headers, config)
{
});
or else you can even use $http's get method to for http get calls.
var config = {};
$http.get('http://localhost:9090/quote', config)
.success(function(data, status, headers, config) {})
.error(function(data, status, headers, config) {});
To know more, read - https://docs.angularjs.org/api/ng/service/$http#get
A note - content-type header is usually sent in http request header while making an POST/PUT call to specify the content type sent from client to server. In your case, you may not need the header.
To know more read - http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

JavaScript functions confusion

I am in the process of learning AngularJS, and have the following code (from video tutorials I'm going through).
eventsApp.controller('EventController',
function EventController($scope, eventData) {
eventData.getEvent(function(event) {
$scope.event = event;
});
I am confused about this bit of the JavaScript eventData.getEvent(function(event) { } I admit that my JavaScript knowledge isn't super, but JavaScript functions are so strange in this regard compared to C# or Java functions/methods.
I understand that eventData is my AngularJS service and on that, I have a method called getEvent() but that does not take in an event object as a parameter! Here is my AngularJS service code:
eventsApp.factory('eventData', function($http, $log) {
return {
getEvent: function(successcb) {
$http({ method: 'GET', url: 'data/event/1.json' }).
success(function(data, status, headers, config) {
successcb(data);
}).
error(function(data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});
Even when I tell myself "ignore object types and classes (thinking along C# / Java lines) and think of it as a plain object", then still I don't get where the event parameter in eventData.getEvent(function(event) { } came from!
Can someone please clarify?
Thanks
You're not actually passing event as the parameter, you're passing that entire function as the parameter as a callback. When getEvent reaches .success, it's calling that function (called successcb in the service), and passing data (where data is actually the event parameter that you're seeing in your controller.
It actually looks more like this:
eventsApp.factory('eventData', function($http, $log) {
return {
getEvent: function() {
$http({ method: 'GET', url: 'data/event/1.json' }).
success(function(data, status, headers, config) {
// successcb(data);
// this is essentially what's happening, except in your controller...
// ...so, this won't actually work because you don't have $scope in this service
// but it's the same idea
successcb(data);
var successcb = function(event) {
$scope.event = event;
};
}).
error(function(data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});
Javascript functions can be treated as inline objects and can be passed as parameters.
for example you can have something like the below (pseodo code):
var x = function fun(){alert ('hi');};
callerFunction(x);
which is same as
callerFunction(function fun(){alert ('hi');});
Above is what is the concept behind and all modern JS libraries (like jQuery) leverage it to include all callback functions as parameters.
Your service method is waiting for variable REFERENCE_TO_FUNCTION.
Maybe this example will make it more clear:
eventsApp.factory('eventData', function($http, $log) {
return {
getEvent: function(REFERENCE_TO_FUNCTION) {
$http({ method: 'GET', url: 'data/event/1.json' }).
success(function(data, status, headers, config) {
REFERENCE_TO_FUNCTION(data);
}).
error(function(data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});

Categories

Resources