I have a small question as follow: I have a function that it takes on values input and returns JSON string. In my function GET_PRODUCT input a parameter as string #product_name . The result as JSON , I do not know how to pass parameters in here . I must declare how do use dataSrc in here (suppose webmethod GET_PRODUCT is work with parameter input )
var table;
table = $('#div_table').DataTable({
"processing": false,
"serverSide": false,
"ajax": {
"url": "../BUS/WebService.asmx/GET_PRODUCT",
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "POST",
dataSrc: function (json) {
//dataSrc: function (json(Candy)) {
//transfer parameter in here
//result as JSON string will parsed and fill in DataTables
return $.parseJSON(json.d);
},
//dataSrc: "Candy",
},
I do not understand the issue pass parameters in here. Please share with me.
Thank guys.
Ok, it work follow
"ajax": {
"url": "../BUS/WebService.asmx/GET_PRODUCT",
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "POST",
data: function (data) { return "{'product_name':'Candy'}"; },
dataSrc: function (json) { return $.parseJSON(json.d); }
},
You can extend the default data being send to the server by using the data parameter e.g.
"data": function ( d ) {
return $.extend( {}, d, {
"product_name": "Candy"
} );
The dataSrc parameter lets you manipulate the data that was being returned from the server. This can either be a string definining the property from the object being returned or a function which will have a single parameter, the JSON returned from the server.
"dataSrc": function ( json ) {
for ( var i=0, ien=json.length ; i<ien ; i++ ) {
// manipulate the returned data in here!
}
return json;
}
You can find more information on the ajax DataTable settings here.
Good luck.
Related
I just want to pass list of integer values to read() method.
used "parameterMap" to map parameter. also tried to set data object.
transport: {
read: {
url:
"#Url.HttpRouteUrl("ActionApi", new {controller = "Regions",action = "GetByCountries" })",
//dataType: "json",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (options, operation) {
debugger;
if (operation === "read") {
return { countries: selectedCountries};
}
}
},
my Controller like bellow
[System.Web.Http.ActionName("GetByCountries")]
[System.Web.Http.HttpGet]
public List<Region> GetByCountries(List<int> countries)
{
return new RegionMgt().GetByCountries(countries).ToList());
}
gives null value for countries parameter.
This Work for me :)
transport: {
read: function(options) {
$.ajax({
type: "POST",
url: "#Url.HttpRouteUrl("ActionApi", new { controller = "Regions", action = "GetByCountries" })",
data: JSON.stringify(selectedCountries),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
options.success(result);
}
});
}
},
Hope anyone help...!
I have 2 API requests. 1st one is GET, that returns a response. This response is used as a Body/Payload in the 2nd request (POST). BUT the Payload should have certain values to be replaced before used in the 2nd request (in my case below it should be value for "Status" property).
How can I do it?
Here is my example Response:
{
"Variations":[
{
"ItemIds":[
"xxx"
],
"Items":[
{
"Id":"67-V1",
"GuId":"xxx",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 1",
"Id":"67-V1"
},
{
"ItemIds":[
"yyy"
],
"Items":[
{
"Id":"67-V2",
"GuId":"yyy",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 2",
"Id":"67-V2"
},
{
"ItemIds":[
"zzz"
],
"Items":[
{
"Id":"67-V3",
"GuId":"zzz",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 3",
"Id":"67-V3"
}
],
"ItemIds":[
],
"Items":[
],
"Name":"MAINP",
"Id":"67",
"Color":null
}
Here is my code, but it does not seem to work (the replacement part):
var jsonData = pm.response.json();
function replaceStatus() {
_.each(jsonData.Variations, (arrayItem) => {
if(arrayItem.Items.Status !== "NonActive") {
arrayItem.Items.Status == "NonActive";
console.log("arrayItem " + arrayItem);
}
});
}
pm.test("Run Function", replaceStatus ());
pm.sendRequest({
url: 'localhost:3000/post',
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res)
})
I guess you are trying to replace all NonActive values with Active. In that case, you should use = for assignment not ==. The JSON file you provided is not valid and couldn't run your code on my machine. I am happy to have a closer look if that didn't work
Based on your updates these changes need to be made
1- in order to deal with JSON object you need to parse the response as it is string and you can't call sth like JsonData.Variations on that.make sure jsonData is a JSON object. if not add sth like this to parse it
var parsedJson = JSON.parse(jsonData)
2- It seems that you missed one array layer in your function to iterate over items. As you have two nested arrays to reach Status the replaceStatus function should be as below
function replaceStatus() {
_.each(parsedJson.Variations, (arrayItem) => {
_.each(arrayItem.Items, (item) => {
if(item.Status !== "NonActive") {
item.Status = "NonActive";
console.log("arrayItem " + item.Status);
}
});
});
}
Have you posted your entire code in the tests section or only a part of it?
I saw from one of your comments that you cannot see the output logged to the console.
This may be very trivial, but, if you did post your entire code, it looks like you may have forgotten to call your replaceStatus() function before your post call.
I am using Select2 4.0.3 in my web forms .net application. I am trying to Load Remote data using a webservice, but its not working as expected.
First Issue am facing is that the webservice method is not getting called and am getting a console error:
System.InvalidOperationException: Missing parameter: text.
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
So I tried removing the paremeter from the webservice call
<WebMethod()> _
Public Function GetDataFromService() As String
Doing this the method got fired, but still the items in the select2 did not get populated (screenshot atached).
Can someone help me to figure out where am I making a mistake.
Here are the details:
Select2 Code in the Webform:
$("#ddlEntity").select2({
ajax: {
url: "Service/InvoiceHTMLService.asmx/GetDataFromService",
type: 'POST',
delay: 250,
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return {
text: term,
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
WebService Method:
<WebMethod()> _
Public Function GetDataFromService(text As String) As String
Return "{['id':1, 'text':'Test1'],['id':2, 'text':'Test2']}"
End Function
Try this please
var fd = new FormData();
fd.append("text",term);
ajax: {
url: "Service/InvoiceHTMLService.asmx/GetDataFromService",
type: 'POST',
delay: 250,
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: fd
...
I think you did not create template for this select2. since you are using templateResult and templateSelection it requires template or you can remove those two options.
For your reference : https://select2.github.io/examples.html#templating
Updated:
they have changed query callback from
data: function (term, page) {
return {
text: term,
};
},
into
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
I am trying to figure out how to insert dynamic data into a dynamodb table via an API Gateway in AWS. Currently I have a dynamodb table and an API endpoint setup that accepts a POST like so.
POST https://{unique-id}.execute-api.us.east-1.amazonaws.com/notification/events
{
"reference_number": 99,
"purchase_date": "1/1/2017"
}
I've setup a body mapping template in the API gateway to massage the data into the dynamodb.
{
"TableName": "Events",
"Item": {
"reference_number": {
"N": "$input.path('$.reference_number')"
},
"purchase_date": {
"S": "$input.path('$.purchase_date')"
}
}
}
The above works and saves to the table.
Suppose I add the event hash to my json (which can change based on events).
{
"reference_number": 99,
"purchase_date": "1/1/2017",
"event": {
"name": "purchase",
"items": [1,3,6],
"info": {
"currencyID": "USD",
"countryID": "US"
}
}
}
How do I save the event attribute to a Map in dynamodb using the API Gateway Body mapping template syntax?
{
"TableName": "Events",
"Item": {
"reference_number": {
"N": "$input.path('$.reference_number')"
},
"purchase_date": {
"S": "$input.path('$.purchase_date')"
},
"event":{
"M": "$input.path('$.event')"
}
}
}
The above template gives me the following error. "Expected map or null"
It looks like DynamoDB API actually requires the value of an 'M' attribute to be a Map of String -> AttributeValue. Unfortunately you can't pass the raw JSON. You'll have to manually map the whole event object to make the DDB API happy.
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-M
One possible workaround would be to stringify the event object and write it as type S but that would of course require the reader to expect that behavior.
{
"TableName": "Events",
"Item": {
"reference_number": {
"N": "$input.path('$.reference_number')"
},
"purchase_date": {
"S": "$input.path('$.purchase_date')"
},
"event":{
"S": "$util.escapeJavaScript($input.json('$.event'))"
}
}
}
As it seems you finally did. I reckon the best option is to create a simple lambda function between you API and dynamoDB. Leaving the mapping work up to the aws-sdk.
In that case, the body mapping template in the API gateway would be as simple as this:
$input.body
And the function won't be much more complicated. I used a javascript function:
var AWS = require("aws-sdk");
var docClient = new AWS.DynamoDB.DocumentClient();
var tableName = "tableName";
var saveData = function (data) {
var params = {
TableName: tableName,
Item: data
};
docClient.put(params, function (err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
};
exports.handler = function (event) {
try {
console.log("Processing event: ", event);
saveData(event);
} catch (e) {
console.error("Processed unsuccessfully", e, e.stack);
}
};
http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.NodeJs.03.html
For my requirement (saving input body), the mapping template is
"rawdata": {
"M": $input.body
}
Note that there are no quotes for input body.
And the data should be in Dynamodb format, for eg
{"username":{"S":"Vishnu"}}
You could use js lib like dynamodb-marshaller to convert json to Dynamodb format. Hope this helps.
This one's killing me. I've read through a lot of Oleg's comments, and through the documentation, but I think I'm overlooking something really simple.
I have a jqGrid populated by calling a webmethod that returns JSON. We're good there. I'm using the Navigator for my "Add" button, and using onSelectRow w/ jqGrid.editRow() for my editing.
I get the dialog box when clicking the "Add" button, and can fill everything in. However, I get a error Status: 'Internal Server Error'. Error code: 500 return message after clicking the Submit button. Using Firebug, the Response is {"Message":"Invalid JSON primitive: FileType.","StackTrace":..... and the Post is FileType=3&ExportDate=12%2F29%2F2010&oper=add&id=_empty.
Obviously, my post is not getting "jsonified". I have tried using serializeEditData, and beforeSubmit in an attempt to manually return JSON.stringify(eparams);, but nothing has worked. Please see my code below.
Webmethod
<WebMethod()> _
<ScriptMethod()> _
Public Sub ModifyFileLog(ByVal FileType As String, _
ByVal ExportDate As Nullable(Of Date), _
ByVal oper As String, ByVal id As String)
Try
' blah
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
JS - Globals
jQuery.extend(
jQuery.jgrid.defaults, {
type: "POST",
mtype: "POST",
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json" },
rowNum: 10,
rowList: [10, 20, 30],
serializeGridData: function(data) {
return JSON.stringify(data);
},
gridview: true,
viewrecords: true,
sortorder: "asc"
},
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function(postData) {
return JSON.stringify(postData);
}
}
);
JS - jqGrid
var tblName = "tblFiles";
var pager1 = '#pagerFiles';
var grid = $("#" + tblName);
grid.jqGrid({
url: 'WebService.asmx/GetFileLog',
colNames: ['ID', 'File Type', 'Report Date', 'Export Date', 'EE Count'],
ajaxGridOptions: {
success: function(data, textStatus) {
if (textStatus == "success") {
ReceivedClientData(JSON.parse(getMain(data)).rows, grid); // populates grid
endGridRequest(tblName); // hides the loading panel
}
},
error: function(data, textStatus) {
alert(textStatus);
alert('An error has occured retrieving data!');
}
},
editurl: "WebService.asmx/ModifyFileLog",
serializeEditData: function(postData) {
return JSON.stringify(postData);
},
recreateForm: true,
pager: pager1,
...
}); // end .jqGrid()
grid.jqGrid('navGrid', pager1, { add: true, del: false, edit: true, view: false, refresh: true, search: false },
{}, // use default settings for edit
{
//beforeSubmit: submitAddFileLog,
closeAfterAdd: false,
closeAfterEdit: true
}, // use default settings for add
{}, // delete instead that del:false we need this
{multipleSearch: false }, // enable the advanced searching
{closeOnEscape: true} /* allow the view dialog to be closed when user press ESC key*/
); // end grid/jqGrid('navGrid')
NOTE: I started out populating by using $.ajax() by way of datatype: function(data), but thought I would return to the simplest example to get this to work. If you care to offer your thoughts on the advantages of using $.ajax() over simply using grid.jqGrid({ url: blah });, I'd love to learn more. Otherwise, please let me know if it would be more appropriate to post it as a separate question.
Also, please let me know if I'm just flat out doing this the wrong way. I'm not locked in to any one way of getting this done. I would prefer to be wrong and to learn how to do this the right way, than to be "right" in my own mind and continue to hack my way through it.
Any help, along w/ examples, would be hugely appreciated.
In my opinion your main problem is in JS - Globals. You use jQuery.extend function in a wrong way. You should replace one call
jQuery.extend(
jQuery.jgrid.defaults, {
// ...
},
jQuery.jgrid.edit, {
// ...
}
);
to two separate calls:
jQuery.extend(
jQuery.jgrid.defaults, {
// ...
}
);
jQuery.extend(
jQuery.jgrid.edit, {
// ...
}
);
After that the edit request to the server will be {"FileType":3,"ExportDate"="12/29/2010","oper":"add","id":"_empty"} instead of FileType=3&ExportDate=12%2F29%2F2010&oper=add&id=_empty.
Next, I am not sure that you can use ExportDate as a Date (DateTime ???) type. Probably you should start with String type and then convert the input data to the datatype which you need.
Next remark. Be sure that ModifyFileLog return JSON data. For example you can use <ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> instead of <ScriptMethod()>. If you use .NET 4.0 you can achieve the same in many other ways.
One more thing. The ModifyFileLog should be Function instead of Sub and return the Id of new added object. In case of edit or del operations the return value will be ignored.
Because ModifyFileLog Function will be returned JSON data you have to decode/parse it. You can do this almost in the same way which I described here. In case of ASMX web service you can do about following:
jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function(postData) {
return JSON.stringify(postData);
},
afterSubmit: function (response, postdata) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
}
);