Getting parserror while sending JSON data to Webmethod - json

I am getting parseerror for my below ajax call, what can be wrong?
<script type="text/javascript" src="json.js"></script>
var contact1 = {
"id":"5",
"name": "fsdfsd"
};
var jsonString = "{\"JsData\":" + JSON.stringify(contact1) + "}";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/ReceiveData",
data: jsonString,
// data: DTO,
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(response,ajaxOptions, thrownError) {
alert("error:" + ajaxOptions);
}
});
My server side webmethod is
[System.Web.Services.WebMethod]
public static string ReceiveData(contact1 JsData)
{
//JsonTextParser parser = new JsonTextParser();
//JsonObject obj = parser.Parse(JsData);
//foreach (JsonObject field in obj as JsonObjectCollection)
//{
// string v = field.ToString();
//}
return "success";
}
public class contact1
{
public int id;
public string name;
}

I got the solution. I am using 2.0 framework, I forgot to add Ajax related references in my web.config. I added those manually, & it worked.

Related

Handling a model returned as json data from a controller in ASP.NET

I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo

How to Serialize Model in View and Pass to Controller Action

I have a very specific need to serialize a model in the view and then pass it to a controller action at some point. I can get it to work by doing several hacks but its not pretty.
My test controller action
public ActionResult Index()
{
DefaultOptionValueRound defaultOptionValueRound = new DefaultOptionValueRound()
{
OptionId = 1835,
OptionValueId = 40343
};
TestModel testModel = new TestModel()
{
DefaultOptionValueRound = defaultOptionValueRound
};
return View(testModel);
}
The View
#using Common.Repository.Extensions
#model EngA.SandboxApplication.Controllers.TestModel
#Html.Hidden("DefaultOptionValueRound", Html.Raw(Json.Encode(Model.DefaultOptionValueRound)))
<input type="button" value="submit" onclick="SerializeModelTest.processOptionMag()"/>
<script language="javascript">
SerializeModelTest = {
processOptionMag: function () {
//Testing: This Works
//var defaultOptionValueRound = { OptionId: 1834, OptionValueId: 4034377 }
//var data = JSON.stringify({ defaultOptionValueRound: defaultOptionValueRound });
//This Does Not Work
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = { defaultOptionValueRound: defaultOptionValueRound }; //Stringify Does not work either
$.ajax({
contentType: 'application/json; charset=utf-8',
type: "Post",
cache: false,
url: '#Url.Action("ProcessOptionMag", "SerializeModelTest")',
data: data,
dataType: "json",
traditional: true,
success: function(data) {
alert(data);
}
});
}
}
</script>
The problem is that the serialized model is returned in a stringify form already.
There must be an elegant way of doing this without me have to do JS string manipulation to make it work.
Thank you for your help
I found out that I can un-stringify my result using JSON.Parse and then repackage it with other parameters for sending to the controller.
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = JSON.stringify({ defaultOptionValueRound: JSON.parse(defaultOptionValueRound) });
Now everything works.

Spring MVC + Ajax error 400

I have a simple java application on Spring MVC and I send ajax request to Spring controller. When I set headers "Accept", "application/json" and "Content-Type", "application/json;charset=utf-8" in AJAX call I get error 400 in dubugger, when I delete it I get error 415.
If I change controller method signature to public String logoutPage (#RequestBody String obyavleniye) I get JSON string. What problem can be with parse request in controller?
JS method:
$("#advertForm").submit(function(e) {
e.preventDefault();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var obyavleniye = {
title: "Title",
price: "80",
description: "desc",
date: "2016-11-07 18:30:21",
authorid: "2",
category: "A",
state: "new",
img1: "http",
img2: "http",
img3: "http",
img4: "http",
};
var post_data = JSON.stringify(obyavleniye);
console.log(post_data);
$.ajax({
url : "/upload",
type: "POST",
dataType: 'json',
data: post_data,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader(header, token);
},
complete: function() {
console.log("Sent");
},
success: function (response) {
console.log("success");
console.log("response" + response);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
Controller method:
#ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String logoutPage (#RequestBody Advert obyavleniye) {
// public String logoutPage (#RequestBody String obyavleniye) {
System.out.println("Enter: " + obyavleniye);
this.advertService.addAdvert(obyavleniye);
// return "{\"msg\":\"success\"}";
return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
}
My sample code.
js
Company.prototype.saveCompanyLocation = function() {
/* company */
var companyIdx = $('#companyIdx').val();
var locationIdx = $('#locationIdx').val();
var data = {
idx : locationIdx,
postCode : $('#postCode').val(),
address : $('#address').val(),
detailAddress : $('#detailAddress').val(),
tel : $('#tel').val(),
fax : $('#fax').val(),
email : $('#email').val(),
language : $("#language").val(),
latitude : $('#latitude').val(),
longtitude : $('#longtitude').val()
};
data = JSON.stringify(data);
$.ajax({
url : "/gpim/company/settings/location/save/" + companyIdx,
type : 'POST',
data : data,
contentType : 'application/json',
success : function(response) {
if (response == "success") {
document.location.reload(true);
} else {
$("#editMsg").text("you can`t save location information.");
}
},
error : function(request, status, error) {
}
});
};
controller
#RequestMapping(value = "/settings/location/save/{companyIdx}", method = RequestMethod.POST)
public #ResponseBody String saveLocation(#PathVariable int companyIdx, #RequestBody CompanyLocation location) {
Company company = companyService.findCompanyByIdx(companyIdx);
company = companyService.saveCompanyLocation(company, location);
if (company != null) {
return "success";
}
return "fail";
}
Do the below steps:
1) try to keep the jackson jar files in your classpath
2) eighter you have remove the datatype while sending ajax request i.e,
dataType : "json"
or you have to produce the application/json response as below
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3) Check your DTO or Advert class properties which type should be matched with incoming request. i.e request params should match with DTO members both names and type.
These are possible ways to avoid your case.

Return json array from client to spring controller

I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});

Json passed is null in MVC controller method

I am doing below to pass Json data to My MVC controller action
Script
var jInput = $("textarea");
var count = 0;
var jsonPackage = "{";
$.each(jInput, function (i) {
jInput[i].style.borderColor = "";
if (jInput[i].value != "") {
if (count != 0) {
jsonPackage += ",";
}
count++;
jsonPackage += "'" + jInput[i].id + "':'" + jInput[i].value.replace(/\\/g, "|").replace(/\'/g, "^") + "'";
}
});
jsonPackage += "}";
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: JSON.stringify(jsonPackage),
dataType: "json",
contentType: "application/json",
success: function (retValue) {
alert(retValue);
}
});
Controller method
public Dictionary<string, Illegal[]> LegalCheck(string jsonPackage)
{
}
Class
[Serializable]
public class Illegal
{
public string Phrase { get; set; }
public int StartIndex { get; set; }
}
For some reason jsonPackage is always null in the controller method. Sample data that s being passed from the script is,
jsonPackage - {'CommentTextarea_1181_1183':'ghhgghhhgd','CommentTextarea_1181_1184':'Coments','CommentTextarea_1181_1185':'comentss'}
What am I doing wrong here? Why am I getting null in my controller method? Please suggest.
Thanks
try
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: {jsonPackage:JSON.stringify(jsonPackage)},
dataType: "json",
success: function (retValue) {
alert(retValue);
}
});
I would guess your JSON string isnt actually being assigned to the jsonPackage variable and so isnt being picked up by your model binder.
for a quick fix try
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: "jsonPackage="+JSON.stringify(jsonPackage),
dataType: "json",
contentType: "application/json",
success: function (retValue) {
alert(retValue);
}
});