How to receive json data from html - json

I want to send some Json data from html to my c# controller. I need it because i want to generate PDF file from this data. I can't find any solution to this problem. Here is how my posting looks:
function sendJSONData() {
var stringToSend = generatePdf();
try {
$.ajax({
type: "POST",
cache: false,
data: stringToSend,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert(e);
};
function getSuccess(data, textStatus, jqXHR) {
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
};
}

Code snippet from some of my projects, use as an orientation:
<script type="text/javascript">
$(function () {
$("#button").click(function () {
var json = #Html.Raw(Json.Encode(object));
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('.cartbadge').html(result.data);
for (i = 0; i < 2; i++) {
$('.cartbadge')
.animate({ marginTop: '-=' + '10px' }, 100)
.animate({ marginTop: '+=' + '10px' }, 100);
}
setTimeout(function () {
$('.default-navbar').load('/Home/ReturnPartialNavbar');
$('#cartModalHolder').load('/Home/ReturnPartialCartModal');
}, 400);
},
error: function (result) {
alert(result);
}
});
});
});
</script>
You are not specifying an url to your controller. How should your script know where to send your data? ;)

Related

jQuery ajax POST, error 'SyntaxError: Unexpected end of JSON input'

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

Highcharts with ajax/ json and SQL Server ASP.NET

I am new to Highcharts and Json data. I am trying to draw pretty simple column chart but failing to do so. below is my code.
HTML:
<div id="container"></div>
Javascript:
$(document).ready(function () {
$.ajax({
url: 'HighCharts.aspx/GetServices',
type: 'POST',
async: true,
dataType: 'json',
contentType: 'application/json',
data: '{}',
success: function (response) {
DrawServices(response.d);
},
error: function () {
window.open("ErrorPage.aspx", "_self")
}
});
});
function DrawServices(data) {
debugger;
if (data == null) {
window.open("ErrorPage.aspx","_self")
}
else {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Services Data'
},
xAxis: {
categories: data[0].Name
},
yAxis: {
title: {
text: 'Total Servcies Requested'
}
},
series: data[0].Total
});
}
}
JSON response
[{"Name":"Access the company internet","Total":489},{"Name":"Application Enhancement","Total":97},{"Name":"Catering Service","Total":250},{"Name":"Desktop","Total":350},{"Name":"Development and Consultation","Total":566},{"Name":"Email","Total":175},{"Name":"Laptop","Total":200},{"Name":"Maintenance","Total":32},{"Name":"Push Email","Total":700},{"Name":"Vehicle Sticker","Total":1200}]
Please guide me what i am doing wrong. blank chart is displaying
You can set x-axis type to category and map your data to the format required by Highcharts, for example: [point.name, point.y]
xAxis: {
type: 'category'
},
series: [{
data: data.map(el => [el.Name, el.Total])
}]
Live demo: http://jsfiddle.net/BlackLabel/r709soxe/
API Reference:
https://api.highcharts.com/highcharts/xAxis.type
https://api.highcharts.com/highcharts/series.column.data

Update item in another site collection in sharepoint 2013

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": "*"
},

Error processing request stream. JSON text specified is not valid

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

JSON output showing additional tag <?xml version="1.0" encoding="utf-8"?> how to remove

JSON output showing additional tag <?xml version="1.0" encoding="utf-8"?> how to remove because it is working with IE but not with any other browser.
$.ajax({
type: "GET",
url: "http://xxx.xxx.xxx.xx/zzz/abc.asmx/method",
data: {},
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: "jsonp",
jsonp: "jsoncallback",
jsonpCallback: "SMS",
cache: true,
success: function (msg) {
var c = eval(msg.d);
for (var i in c) {
treminalId = c[i]['DDD'];
console.log(DDD);
}
},
error: function (msg) {
alert(JSON.stringify(msg));
}
});
try this one
$.ajax({
type: "GET",
url: "http://xxx.xxx.xxx.xx/zzz/abc.asmx/method",
data: formToJSON(),
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: "jsonp",
jsonp: "jsoncallback",
jsonpCallback: "SMS",
cache: true,
success: function(msg) {
var c = eval(msg.d);
for (var i in c) {
treminalId = c[i]['DDD'];
console.log(DDD);
}
},
error: function(msg) {
alert(msg);
}
});
function formToJSON() {
return JSON.stringify({});
}