Invalid JSON primitive when sending POST request of stringify objects - json

I have ajax function where i am sending two stringify objects like this:
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var BookObj = JSON.stringify({ obj: viewName })
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
var OffsetCommonObj = JSON.stringify({ 'OffsetCommonObj':
OffsetCommonModel });
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: OffsetCommonObj + '&' + $.param(BookObj),
dataType: 'json',
success: function (data) {
}
});
this is my action method :-
public ActionResult CreateOffset(OffsetCommonModel OffsetCommonObj, CalculationModel obj)
{
// do something with objects
}
but when i check in the console its giving error "Invalid JSON primitive"
where i am doing wrong please help..Thanks

Your data part in ajax should be something like this and no need to stringify objects individually, do that once
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
// var BookObj = { obj: viewName }
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
// var OffsetCommonObj = { 'OffsetCommonObj': OffsetCommonModel };
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: JSON.stringify({ 'OffsetCommonObj': OffsetCommonModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
}

Related

ajax result data empty

I'm getting data as json result from controller.
But in my ajax that data is empty. Why?
Controller:
public JsonResult GetMealType(string mType)
{
var obr = new Obroci();
var obrGrid = obr.GetMealType(mType);
return Json(obrGrid, JsonRequestBehavior.AllowGet);
}
Json variable has value.:
string:
[{"Type":"M1","Price":25,"Description":"Topli obrok"}]
ajax :
var newText = $('option:selected', this).text();
$.ajax({
url: "/Dumas/GetMealType?mtype=" + newText,
type: "POST",
data: 'json',
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
You must correct your Ajax code to:
$.ajax({
url: "/Dumas/GetMealType",
type: "POST",
data: JSON.stringify({ mtype: newText }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (data) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});

“Invalid JSON primitive” in Ajax processing MVC

I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks

Get value from an odata property in a JSON response using ajax

I need to get the value for #odata.context property from the following Json response in ajax:
{
"#odata.context":"https://site.sharepoint.com/_api/",
"#odata.type":"#oneDrive.permission",
"#odata.id":"https",
"link":{"scope":"anonymous"}
}
I would like to do something like that in code:
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.#odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1
}
});
I think you can get data by this:
data["#odata.context"]
And about the JSON.parse throw exception, it caused by the data is not a JSON string.
Example

Json responseText empty and statusText as error

From mvc 4 action:
[HttpPost]
public ActionResult DoStuff(string str)
{
// Do some things
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = someCondition == true ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return Json(
new {
object1 = 1,
object2 = someArray[0],
object3 = someArray[1],
object4 = someValue == 4 ? 1 : 0
}
);
}
In jquery ajax:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
var _response = $.parseJSON(data);
}, function (data) {
var _response = $.parseJSON(data.responseText);
});
data.responseText is empty ("") and statusText is "error". It is not always happening. I have observed that it is happening randomly. Why?
Your data is already being converted to an object from JSON, so you do not need to parse it again. Try this:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
// use data here...
alert(data.object1);
}, function () {
alert('request failed');
});

JSON Redirect from MVC Controller not working

I've tried the steps outlined in other posts here
and here and it just doesn't work. I end up getting redirected to a white screen that just says ... {"redirectTo":"/Administrator/Home"}
C#
[HttpPost]
public JsonResult ControllerMethodHere(ViewModel model) {
// my controller code goes here.
return Json(new {
redirectTo = Url.Action("Index", "Home"),
}, JsonRequestBehavior.AllowGet);
}
Javascript
this.save = function () {
$.ajax({
url: $('form').attr('action'),
type: "POST",
data: ko.toJSON(this),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data.redirectTo;
}
});
};
Try using this:
window.location = data.redirectTo;