“Invalid JSON primitive” in Ajax processing MVC - json

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

Related

Json result to table

I Would like when doing the search the results to be inputed to a table my results are being taken from my web service table
function DoSearch() {
$("#resultsDiv").html("");
var key = { "key": $("#SearchString").val() };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Stadium.asmx/GetStadiumByName",
data: JSON.stringify(key),
dataType: "json",
async: true,
success: function (result, textStatus) {
if (textStatus == "success") {
for (var i = 0; i < result.d.length; i++) {
$("#resultsDiv").html($("#resultsDiv").html() + result.d[i] + "<br/>");
}
}
},
error: function (result, status, error) {
$("#resultsDiv").html("Error: " + error + " <br/>")
}
});
}
Below is my webservice file this gets all the information im looking for in my search.
[WebMethod]
public object[] GetStadiumByName(string key)
{
List<object> stadiums = new List<object>();
if (key != "")
{
foreach(var Name in db.Stadiums
.Where(a => a.Name.Contains(key))
.ToList())
{
stadiums.Add(Name.Name);
stadiums.Add(Name.Location);
stadiums.Add(Name.Team);
stadiums.Add(Name.Capacity);
}
}
return stadiums.ToArray();
}
}
The search returns the following I want to put that information in a table

When Passing checkbox values as JSON in Jquery, I get an error: 500 Internal Server

I want to pass a checkbox value with JSON, but when debugging my code I get this error:
NetworkError: 500 Internal Server Error - http://localhost:2020/LabAccess/LabAccesscheck"
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
What's the problem? I use this code in view and control.
$(function () {
$("#GetAccess").change(function () {
alert('asa')
var newValue = true;//$(this).checkbox;
var itemID = '2' ;
alert('ii')
$.ajax({
type: "post",
url: "/LabAccess/LabAccesscheck",
data: { itemID: '67' },
datatype: "json",
traditional: true,
success: function (Data) {
//alert(data.itemID);
//alert(data.itemID);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
});
});
[HttpPost]
public virtual JsonResult LabAccesscheck(string itemID)
{
//Int16 ID = Convert.ToInt16(TempData["id"].ToString());
TempData["fulname"] = _UserService.getfullname(36);
string type = string.Empty;
IList<P_User_Get_Lab_Access_List_Result> selected = _ILabAccess.GetDataTablebyUser(36, "Userid");
//return (PartialView(MVC.BaseAdmin.LabAccess.Views._ListbyUser, selected));
return Json(PartialView(MVC.BaseAdmin.LabAccess.Views._ListbyUser, selected), JsonRequestBehavior.AllowGet);
}

reCAPTCHA ajax verification ReferenceError: success is not defined

I am getting an error when I post my ajax call to the reCAPTCHA verification API. I get a "ReferenceError: success is not defined" error on correct input and "ReferenceError: incorrect is not defined" on incorrect insertion of the CAPTCHA. Here is my code:
$.ajax({
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
url: "http://www.google.com/recaptcha/api/verify",
data: {
privatekey: 'XXXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
async: false,
success: function (resp) {
if (resp == "false") {
alert('Please enter captcha words correctly');
reloadRecaptcha();
}
else {
alert('Yeah');
}
}
});
Well I solved my own problem by sending the post data to the page controller.
JS:
$.ajax({
type: 'GET',
contentType: "application/json",
url: "/Register/veriCAPTCHA",
data: {
privateKey: 'XXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
success: function (data) {
if (data == false) {
valiCAPTCHA = false;
ALERT("The CAPTCHA code you entered is invalid. Please try again.");
Recaptcha.reload();
}
else {
valiCAPTCHA = true;
}
}
});
CS controller:
[HttpGet]
public JsonResult veriCAPTCHA(string privateKey, string remoteip, string challenge, string response)
{
string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey, remoteip,
challenge, response);
JsonResult result = new JsonResult();
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
try
{
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
//incase you are using a proxy server
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
jsonResponse = sr.ReadToEnd();
string[] tokens = jsonResponse.Split(new char[] { '\n' });
if (tokens.Length == 2)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

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

Calling a webservice from jQuery returns “No Transport” error

I have the following web service;
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
I am pointing to the latest jquery library.
<script type="text/JavaScript" src="Scripts/jquery-1.6.4.js"></script>
I have this jQuery method;
$.ajax({
type: "POST",
url: "../Service/AFARService.asmx/HelloWorld",
// this._baseURL + method,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
crossDomain: true,
dataFilter: function (data) {
var response;
if (typeof (JSON) !== "undefined" && typeof (JSON.parse) === "function")
response = JSON.parse(data);
else
response = val("(" + data + ")");
if (response.hasOwnProperty("d"))
return response.d;
else
return response;
}
});
When I execute I get a "No transport" error returned. I added crossDomain: true still no success.
Thanks in advance
BB
to enable cross domain calls, you can try
jQuery.support.cors = true;
if this doesn't works you can go through(JSONP) :
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
https://en.wikipedia.org/wiki/JSON
http://remysharp.com/2007/10/08/what-is-jsonp/
you can follow any of these
try using
url: "AFARService.asmx/HelloWorld",
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}