I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
Related
I'm sure I'm missing something simple, but so far struggling to see what...
I am wanting to POST some form field entries to a server in JSON format.
I am currently using:
$(document).ready(function () {
$("#newEnquiry").submit(function (event) {
event.preventDefault();
$.ajax({
url: 'SERVER-URL-HERE',
type: 'POST',
data: JSON.stringify({ "name": $('#name').val(), "emailAddress" : $('#emailAddress').val(), "address" : $('#address').val() }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data, textStatus, jQxhr){
console.log('Sent');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log('fail');
console.log(errorThrown);
}
});
});
});
The error that I am being shows in the console is:
SyntaxError: Unexpected end of JSON input
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "POST",
data: JSON.stringify({
name: "test",
emailAddress: "test",
address: "test",
}),
contentType: "application/json",
dataType: "json",
success: function (data, textStatus, jQxhr) {
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("fail");
console.log(errorThrown);
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
contentType has to be application/json and you should pass a plain json into the JSON.stringify method into the data attribute. So the code has to be:
$(document).ready(function () {
$("#newEnquiry").submit(function (event) {
event.preventDefault();
$.ajax({
url: 'SERVER-URL-HERE',
type: 'POST',
data: JSON.stringify({ name: $('#name').val(), emailAddress : $('#emailAddress').val(), address : $('#address').val() }),
contentType: 'application/json',
dataType: 'json',
success: function(data, textStatus, jQxhr){
console.log('Sent');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log('fail');
console.log(errorThrown);
}
});
});
});
I am trying to send a push notification using onesignal.In that process i got an error
"error":"There was a problem in the JSON you submitted: unexpected character at line 1, column 1 [parse.c:652]"}
My Code is as follows:
var jsonBody = {
"app_id": "OneSignal App ID",
"include_player_ids": ["Onesignal Playerid"],
"headings": {
"en": "Sump"
},
"contents": {
"en": " Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: jsonBody,
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
Can anyone help me where i am going wrong.
Thankyou.
Hi try to create an object then stringfy it to json.
var jsonBody =
{
app_id: "OneSignal App ID",
include_player_ids: [ "Onesignal Playerid", "Secondsignal Playerid"],
headings :
{
en: "Sump"
},
contents :{
en: "Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: JSON.stringify(jsonBody),
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
I used this code
function updateListItem(itemId, listName, siteUrl, title, success, failure) {
var metatdata = "{ '__metadata': { 'type': 'SP.Data.TestListListItem' }, 'Title': "+title+"}"
getListItemWithId(itemId, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
dataType: "json",
contentType: "application/json;odata=verbose",
method: "POST",
body: metatdata,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Length":metatdata.length,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
alert("success in ajax");
console.log("Item in success ajax");
console.log(data);
success(data);
},
error: function (data) {
alert("waiting for success in ajax");
console.log("Item in error ajax");
console.log(data);
failure(data);
}
});
}, function (data) {
failure(data);
});
when i checked it using console,it shows "Error processing request stream. JSON text specified is not valid",I think i can't able to read text value from JSON Response and I tried lot.Please help me guys..Thanks in Advance
function updateListItem(itemId, listName, siteUrl, title, success, failure) {
getListItemWithId(itemId, listName, siteUrl, function (data) {
var item = { '__metadata': { 'type': 'Microsoft.SharePoint.DataService.TestListItem' }, 'Title': title };
$.ajax({
url: data.__metadata.uri,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}, function(data){
failure(data);
});
}
function getListItemWithId(itemId, listName, webUrl, success, failure) {
$.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
Hi I am making the call for alchemy sentiments API as given below:
function getAnalysis(sentence)
{
$.ajax({
url:alchemy.baseUrl,//http://access.alchemyapi.com/calls/text/TextGetTextSentiment`enter code here`
type: 'POST',
dataType:'jsonp',
contentType:'json',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
outputMode:'json'
//outputMode:'xml'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
I am getting status 200 OK. But error in parsing : is returned from ajax call. I have validated JSON it is correct.The json is below:
{
"status": "OK",
"usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html",
"url": "",
"language": "english",
"text": "sachin is a good batsman.",
"docSentiment": {
"type": "positive",
"score": "0.50098"
}
}
Please help me.
I have solved the question just by modifying the ajax request and adding the callback as given below:
function getAnalysis(sentence)
{
$.ajax({
url: alchemy.baseUrl,
type: 'POST',
dataType:'jsonp',
contentType:'json',
jsonpCallback:'callback',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
jsonp:'callback',
outputMode:'json'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
var text=data.text;
if(data.docSentiment.type==="negative")
{
displayNegetiveAnalysis(text);
}
else if(data.docSentiment.type==="positive"){
displayPositiveAnalysis(text);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
}
/*
* Function:Callback
* Description:passing callback to URL Call
*
*/
function callback(json){
console.log(json);
}
I am trying to get some data from a web service:
$.ajax({
type: 'POST',
url: "http://192.******.asmx?op=GetJSONString",
method: "serverCallback",
data: "Select con.cod as codigo, con.res as descripcion from con where ide>0",
success: function(data){alert(data)},
});
How can I get the returned JSON data?
Here is what my calls look like. Can you be more specific of the issue you are having?
$.ajax({
type: "POST",
data: "SOME DATA",
dataType: "json",
url : "/myapp/service.json",
cache: false,
error: function() {
alert("There was an issue");
}
,
success: function(data)
{
processJson(data);
}
});
I will also post what has worked with me for asmx services.
In the example below, for "url": "/service/Details.asmx/Reject", the "/Reject" is the method name in the web service (asmx) file.
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": "/service/Details.asmx/Reject",
"data": "{\"itemId\":\"" + id + "\",\"comment\":\"" + comms + "\"}",
"success":
function (msg) {
alert("Yea it worked!");
});
}
});