Pass Date from View to Controller with JSON - json

I am trying to pass the date by ajax to controller as below:
$.ajax({
type: "POST",
contentType: 'application/json',
url: '/UserReport/GenerateReport',
data: JSON.stringify({
'clientId': $('#reportClientDropdown').val(),
'dateFrom': $('#datePickerFrom').val(),
'dateTo': $('#datePickerTo').val()
}),
success: function (succ) {
//
},
error: function (data) {
}
});
dateFrom and dateTo are in format dd/mm/yyyy.
I am getting 500 error after this call. Here is my controller
public JsonResult GenerateReport(int userId, int clientId, DateTime dateFrom, DateTime dateTo)
Is there a problem with DateTime parameter?

specify ajax request datatype jQuery.ajax()
$.ajax({
url: '/UserReport/GenerateReport',
type: "POST",
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
'userId': 1,
'clientId': $('#reportClientDropdown').val(),
'dateFrom': $('#datePickerFrom').val(),
'dateTo': $('#datePickerTo').val()
}),
success: function (result) {
console.log(result);
},
error: function (xhr) {
alert('Error: ' + xhr.statusText);
}
});

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

How to pass a json file through ajax as Multipart and retrive the file in servlet (jsp)

Please find the code,
json = JSON.parse(e.target.result);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "jsnservlt",
data: json,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function(dataa) {
var resp =JSON.parse(data);
console.log(resp);
alert(dataa);
},
error: function(error) {
console.log(error);
}
});
How to retrieve the json in servlet?

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

Why is the update operation not posting any data?

I am using the Kendo Grid with inline editing. When I click the "Update" button, a POST gets made to my controller method with this signature. The controller action gets hit, so the POST is working.
[HttpPost]
public HttpResponseMessage SaveAccountAdmin(string jsonCompanyContacts)
However the POST data in the update operation never arrives - its always null.
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
Here is the FULL data source code.
var dataSource = new kendo.data.DataSource(
{
batch: false,
pageSize: 10,
transport: {
create: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
read: {
url: "/Company/ReadAccountAdmin"
},
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
},
this doesnt work either:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
BUT THIS WORKS- WHY?
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
//data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify({ "jsonCompanyContacts": "John Doe" });
}
The value is not passed to the controller as a string. Try using a model. This might help: MVC3 & JSON.stringify() ModelBinding returns null model
UPDATE
You really don't want to do it like that. Might work in theis one case, but you are shooting yourself in the foot.
Model
public class CompanyContactModel
{
public string CompanyContacts { get; set; }
}
Controller Signature
public JsonResult SaveAccountAdmin(CompanyContactModel companyContactModel)
...
Better
public JsonResult SaveAccountAdmin([DataSourceRequest]DataSourceRequest request, CompanyContactModel companyContactModel)
...
Update and Return and put into List
If error: ModelState.AddModelError(string.Empty, e.Message);
DataSourceResult result = [Your Model List].ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
Try doing this in your update definition:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data:{ "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" })}
}
You might have to remove the operation in your parameterMap for this to work. The main thing is that you want to post a variable with the same name as in your controller. That variable should contain your stringified data.
You could also move this operation to your parameterMap if you want.
I had similar problem like you.I am getting values from the broswer , but its not posting the values to the update action model.
In my case I used "[ScriptIgnore(ApplyToOverrides = true)]" on the model which works fine.

how connect with web service

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