Update empty field to contain value - rest API - sharepoint-2013

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>

Related

AJAX POST request error - `Uncaught TypeError: Illegal invocation`

If I try to do this, I get this error:
Uncaught TypeError: Illegal invocation
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
And if I try to do this, I get this error:
403: Forbidden
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
processData: false,
contentType: false,
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
# This is my views.py
def search(request):
return JsonResponse(data={
'test': 'test'
})
What could be the problem?
Your help is greatly appreciated. Thank you
I am so sorry that I bothered everyone.
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
I had done this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]')
But should do this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

How to pass List<int> to kendo grid read()

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...!

sendRequest does not seem to use Headers values I specify in the Test

I'm using sendRequest function to send a 2nd request as part of the Test for my 1st request. But it seems that sendRequest does not use the Headers I specify in the function. Any ideas why and how to fix it?
Here is part of my Test, that sends 2nd request:
var runHost = pm.environment.get("MyHost");
var runToken = pm.environment.get("Token");
pm.sendRequest({
url: runHost,
method: 'PUT',
headers: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});
Here is what I see as an actual Request Headers sent (what I see in Console):
PUT https://some_url
Request Headers:
Content-Type:"text/plain"
User-Agent:"PostmanRuntime/7.15.2"
Accept:"*/*"
Cache-Control:"no-cache"
Postman-Token:"5e3543c-1ww0-dfc4-bert-92ba9a455667"
Host:"my_host"
Accept-Encoding:"gzip, deflate"
Content-Length:1876
Connection:"keep-alive"
I expect Request Headers to have the following attributes and values:
Authorization:"Auth current_token_value"
Accept:"application/json"
Content-Type:"application/json"
...
The key for the object that contains the Request Headers should be header, like in the example below:
pm.sendRequest({
url: runHost,
method: 'PUT',
*header*: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});

Implementing Batch Update in Kendo UI GRID not work

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);
}
});
}

Django CSRF 403

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!");
}
})