I'm not sure what's the issue, but I'm constructing a string and trying to pass it to my Controller Action. But when the action is executed, the data is null.
JavaScript:
var xml = "<Request><ZipCode>92612</ZipCode></Request>";
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: xml,
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});
Controller:
[HttpPost]
public ActionResult GetXml(string data)
{
if (!String.IsNullOrEmpty(data))
{
return View("Index", data);
}
return View("Index");
}
If I set a breakpoint on the if, the "data" is null. What gives?
The answer: don't use contentType
Thanks to this question and answer:
Asp.Net Mvc JQuery ajax input parameters are null
try with
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: { data: xml },
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});
Related
I want to parse the below JavaScript array for using in Autocomplete control.
The requirement is to display the value field in autocomplete textbox and store the key field as itemID.
{"Key":9886,"Value":"xxx"},{"Key":9887,"Value":"yyy"},{"Key":5634,"Value":"zzz"},{"Key":9888,"Value":"abcd"}
I tried the below code to map this array as source for my textbox:
var itemID;
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data:JSON.stringify({'term' :request.term}),
dataType: 'json',
contentType: 'application/json',
success: function(data) {
response(
$.map(data,
function(object) {
return {
label: object.value,
value: object.key
}
})
)
},
error: function(xhr, status, error) {
alert(error);
}
});
},
minLength: 2,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.value);
itemID = ui.item.key;
}
});```
Appreciate any help on this.
The below code worked to map autocomplete source to dictionary array:
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data: JSON.stringify({ 'term': request.term }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var parsedData = JSON.parse(data);
var arr = $.map(parsedData,
function (item) {
return {
label:item.Value,
value:item.Key
}}
);
response(arr);
},
error: function (xhr, status, error) {
alert('here');
var array = [];
response(array);
}
});
},
minLength: 3,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.label);
userID = ui.item.value;
}
});
The controller code which returns dictionary was this:
public ActionResult Getdata(string term)
{
var itemList= Provider.GetAllItems();
var filteredItems = itemList.Where(x => x.Value.Contains(term));
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(filteredItems );
return Json(result, JsonRequestBehavior.AllowGet);
}
I need to make this request but in axios
$.ajax({
type: "POST",
url: url,
data: {'HTTP_CONTENT_LANGUAGE': 'en'},
xhrFields: {
withCredentials: true
},
I tried
params = {
data: {
'HTTP_CONTENT_LANGUAGE': 'en',
},
withCredentials: true
};
axios.post(url, params)
But didn't work what do I do?
i would like to delete item from list in SharePoint 2016. I use SharePoint REST API, but I cannot successfully delete item. This is error message (http code 400):
A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry.A 'StartObject' node was expected.
Here is my code:
$.ajax({
url: 'https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items?$filter=ID eq '5'',
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method-Override": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
What is incorrect? Thanks
Please use below code: It works fine for me :
$.ajax({
url: "https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items(5)",
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
})
Google Analytics v4 API now uses POST requests instead of GET request. And there are no good javascript examples out there yet for me to follow. I'm getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice on what I am doing wrong? or are there any fully working example that I can follow? Thanks.
requestData = function () {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var params = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
I would highly recommend you use the Google Javascript Client Library to simplify your life greatly. There are plenty of Code Samples using said library:
var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';
// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY).then(function() {
// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}).then(null, function(err) {
// Log any errors.
console.log(err);
});
As for getting jQuery to work, a similar question was asked about nodejs Their solution was to set the content-type=application/json which fortunatly has been Asked and answered as well.
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var data = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
I have multiple URL paths that I would like to map to a single resource. However I am unsure how to change the URL based on the function called. For example the :dest mapping for query would be /allProducts, however destroy would be something along the lines of /delete/:id
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/:dest', {}, {
query: {method: 'GET', params: {}, isArray: true },
save: {method: 'POST'},
show: { method: 'GET'},
edit: { method: 'GET'},
update: { method: 'PUT'},
destroy: { method: 'DELETE' }
});
}]);
For each action you can override the url argument.
Specially for this is the url: {...} argument.
In your example:
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/', {}, {
query: {method: 'GET', params: {}, isArray: true },
save: {method: 'POST', url: 'service/products/modifyProduct'},
update: { method: 'PUT', url: 'service/products/modifyProduct'}
});
}]);
I just needed to put the url in as the param.
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/:dest', {}, {
query: {method: 'GET', params: {dest:"allProducts"}, isArray: true },
save: {method: 'POST', params: {dest:"modifyProduct"}},
update: { method: 'POST', params: {dest:"modifyProduct"}},
});
}]);