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...!
Related
So I have a snippet of code that will update a field value if the field has content, although if the field that I'm trying to update is null than the value won't update. Am I doing something wrong?
siteURL = _spPageContextInfo.webAbsoluteUrl;
var apiPath = _spPageContextInfo.webAbsoluteUrl +"/_api/lists/getbytitle('Training%20Copy')/items/getbyid(9)";
$.ajax({
url: apiPath,
type: "POST",
headers: {
Accept: "application/json;odata=verbose"
},
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.Training_x0020_CopyItem"
},
Admin_x0020_Function: "Have content"
}),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
async: false, success: function(data) {
console.log("Item updated successfully");
}, eror: function(data) {
console.log("An error occurred. Please try again.");
}
})
There are two headers parameters in your ajax request, it is not clear whether it will affect.
My test code for your reference:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
Update()
function Update(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(9)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: JSON.stringify({__metadata:{'type':'SP.Data.DocItem'},test:'test'}),
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>
I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);
I have number if files to be added in the zip file. some are optional (user choice). I like to execute the generateAsync once all required files Ajax post is successful.
I tried to place a check but its not working.
SAMPLE CODES:
var requestCSS;
var StyleFileData;
var requestAnimatedJS;
var AnimatedScriptData;
function getAllFiles(complileComplete){
requestCSS = $.ajax({
url: 'css/styles.css',
type: "GET",
contentType: "text/css",
mimeType:'text/plain; charset=x-user-defined',
success: function (data){
StyleFileData = data;
}
});
if(animatedBG){
requestAnimatedJS = $.ajax({
url: 'js/animated.js',
type: "GET",
contentType: "text/javascript",
mimeType:'text/plain; charset=x-user-defined',
//async: false,
success: function (data){
AnimatedScriptData = data;
}
});
} else {
requestAnimatedJS = '';
}
}
$('#saveProject').on('click', function(){
getAllFiles(complileComplete);
if(complileComplete === true) {
var zip = new JSZip();
var jsFiles;
var cssFiles;
zip.file("index.html", fullHTML);
jsFiles = zip.folder("js");
cssFiles = zip.folder("css");
requestCSS.done( function( data ) {
cssFiles.file("styles.css", data, { binary: true });
});
if(animatedBG){
requestAnimatedJS.done( function( data ) {
jsFiles.file("particles.js", data, { binary: true });
});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "Sample.zip");
});
}
});
No server side or node.js is involved.
While trying to perform batch update, I am not able to post values to MVC WEB API controller neither I am getting Record IDs in mu PUT controller.
I have already visited some of the links egarding same problem but got no solution.
$(document).ready(function () {
debugger;
var webapiUrl = (My webapi);
dataSource = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: webapiUrl + api/GetProductsByShipID/1",
contentType: "application/json",
},
update: {
url: webapiUrl + api/OpportunityProducts/1",
contentType: "application/json",
type: "PUT"
},
destroy: {
url: webapiUrl + /api/OpportunityProducts/",
contentType: "application/json",
type: "DELETE"
},
create: {
url: webapiUrl + /api/OpportunityProducts/",
contentType: "application/json",
type: "POST"
},
parameterMap: function (options, operation) {
if (operation !== "read") {
return options;
}
}
},
batch: true,
pageSize: 10,
schema: {
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: true },
ProductDesc: { type: "string" },
Quantity: {type: "number"},
UnitPrice: { type: "number"}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{ field: "ProductDesc", title: "Product Desc"},
{ field: "Quantity", title: "Quantity" },
{ field: "UnitPrice", width: 120 },
{ command: "destroy", title: " ", width:150 }],
editable: true
});
});
</script>
Well after some workaround, late night I was able to modify parameterMap section of my kendo grid which lead me to expected output.
This is how I updated my parameterMap section...
Previous
parameterMap: function (options, operation) {
if (operation !== "read") {
return options;
}
}
Updated
parameterMap: function (options, operation) {
debugger;
if (operation !== "read" && options.models) {
var webapiUrl = (my webapi);
var i = 0;
for (i = 0; i < options.models.length; i++) {
$.ajax({
cache: false,
async: true,
type: "PUT",
url: webapiUrl + "/api/OpportunityProducts/" + options.models[i].Id,
data: {
ID: options.models[i].ID,
ProductDesc: options.models[i].ProductDesc,
Quantity: options.models[i].Quantity
},
success: function (data) {
},
error: function (jqXHR, exception) {
alert(exception);
}
});
}
Getting a CSRF 403. The console.log statements below confirm that I'm grabbing the token. I'm submitting the request to the same domain on my local server.
internal.csrfToken = $.cookie('csrftoken');
internal.csrfSafeMethod = function(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
console.log("ajaxSetup");
console.log(internal.csrfToken);
if (!internal.csrfSafeMethod(settings.type)) {
console.log("Settings type");
xhr.setRequestHeader("X-CSRFToken", internal.csrftoken);
}
}
});
external.submitPayment = function (app_id, charge_now_amount, stripe_plan_id) {
// Submit a payment to the server and handle any errors.
$.ajax({
url: URLS.postPayment,
type: 'POST',
data: {
'app_id': STRIPE_CONFIG.app.id,
'amount': charge_now_amount,
'stripe_plan_id': stripe_plan_id
},
dataType: 'json',
success: function(response) {
alert("Success!");
},
error: function(jqXHR, textStatus, errorThrown ) {
alert("Error!");
}
});
};
not sure if this will help you. I had a similar problem. And fixed it by making a beforeSend functions that's add the X-CSRFToken
$.ajax({
url: url,
data: JSON.stringify({'name': value }),
type: 'POST',
dataType: 'json',
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
},
success: function(response) {
alert("Success!");
}
})