Getting invalid json primitive error in jquery-ajax - json

I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.

The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }

I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.

Related

Unexpected end of JSON input... SO Wants more info

I'm confused... What's wrong with this?
Couldn't post without changing the title... I seriously don't know what's wrong
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {mobname: 1},
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
I looked up here Unexpected end of JSON input from an ajax call
but somehow not what I expected... What's wrong? Thanks.
Try this approach:
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
var data = {}; // setup a data object
data[mobname] = 1; // add the property with the key of the value of the "mobname" variable, with the data of 1 (per question)
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: data, // pass the data object as the POST data instead of defining an object inline
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
Note the lines with comments, above.
In this approach, we setup a data object and specify a property using the value of the "mobname" variable, instead of defining the property inline. This allows us to use the dynamic value of the variable as the key for the property.
I guess the problem is with the line: data: {mobname: 1}
As you can't assign a variable name as object property like that... it should be inside a square brackets like this data: {[mobname]: 1}
EDIT: if you aren't using browser supported by ES 2015 you could even do
data: JSON.parse('{"'+mobname+'":1}')
EDIT 1 if you want to send the json data as string and convert that on php side you could simply do data: '{"'+mobname+'":1}'
This might cause your ajax call to fail, and might not return a JSON as you're expecting (using the line dattype:JSON);
So removing datatype:JSON can also help you by showing what you're doing wrong
JSON objects are differentiated from standard JavaScript objects by using double quoted in both the key and the value - unless either is an integer.
It is explained in the relevant W3Schools site.
Therefore, in your AJAX request, you have to send a properly formatted JSON object:
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {"mobname": 1}, //here's the change
dataType: "json",
/* rest of the code */
You can of course pass a variable as well:
var JSON_obj = {"mobname": 1, "othermob": 2, /*rest of the JSON */ };
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: JSON_obj, //here's the change
dataType: "json",
/* rest of the code */
Again, with properly formatted JSON objects (and with properly included JS script if it's in another file), this should work.

How to call .asmx web service using plain html page

I am trying to call an asmx web service in plain html page. But not getting output. I'm not getting the exact problem. Here is my ajax code that I wrote to call that asmx web service.
function Getdet(Name)
{
alert('hellotest');
$.ajax({
type: "POST",
url: "http://192.168.1.20/myservice/service.asmx?HelloWorld", // add web service Name and web service Method Name
data: "{''}", //web Service method Parameter Name and ,user Input value which in Name Variable.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert('abcd1');
$("#spnGetdet").html(response.d); //getting the Response from JSON
},
failure: function (msg)
{
alert(msg);
}
});
}
Should I have to add anything in the code..?? Please let me know where I am going wrong in this above code.
ASMX pages are plain old Web Services and the output is (almost) always in XML format, so don't except JSON out of the box.
Plus, they don't work well on different domain call by default, you will need to ensure that the cross domain is correctly handled.
After all this is done, you will then use the call as:
success: function(response) {
// http://stackoverflow.com/a/1773571/28004
var xml = parseXml(response),
json = xml2json(xml);
$("#spnGetdet").html(json.d);
}

How to use a list of objects or array in json post request to a WebService?

as described in the title, I'm trying to call a WebService method via JSON/Ajax in JavaScript with several String parameters and 2 lists or arrays.
For now everything worked fine with single parameters in this format:
var WSParameters = "{pParam1: 'abc', pParam2: 'def'}"
$.ajax({
type: "POST",
url: "WebService.asmx/" + webMethod,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: WSParameters,
success: function (result) {
// stuff to be done on if request was successful
},
error: function (message) { alert('Error loading data! ' + message.responseText); }
});
But now I need to provide the web service method a list/array of values. The web service method looks like this:
[WebMethod(true)]
public void editExistingSystem(System.Collections.Generic.List<String> pFirstList,
System.Collections.Generic.List<String> pSecondList,
String pParam1,
String pParam2)
{
// Stuff
}
I guess it should be something like this, but obviously this didn't work:
var WSParameters = "{pFirstList: 15,4,13, pSecondList: 'gr00001_96594737', pParam1: 'abc', pParam2: 'def'}"
Could you please help me with finding the correct syntax to define a list in this parameter list?
Thanks a lot in davance
Br
vm370
As so often, I found the solution almost right after asking the question...
Sorry guys for bothering you. The correct paramter string to the example in my starting post would be:
var WSParameters = "{pfirstList: ['15','4','13'], pSecondList: ['gr00001_96594737'], pParam1: 'abc', pParam2: 'def'}"
Thanks and best regards
vm370

JSON, invalid label, issue consuming JSON

I have an issue with my JSON. We area getting it from a SOAP service I believe. I am using jQuery AJAX to try to consume the JSON. We are using the Asp.NET solution so I know about the "d" security feature and have in my dataFilter a way to try to get around that. I am getting the JSON back in Firebug but not to my local machine. The Service is on a domain separate from my local machine. I know about the cross domain policy issue but seems to be consuming the JSON in Firebug when I put the dataType as "jsonp" in the jQuery AJAX call.
If I set my dataType as "json" I get nothing back in Firebug.
The thing is my JSON has "\" slashes in it. I guess that is why Firebug is giving me an "invalid label" error. But I am not sure of that.
How can I filter out the "\" without doing the server side code again.
How can I just get the JSON back and alert on my page.
My jQuery Ajax call is below.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "http://www.myexternaldomain.com/jservice/myservice.svc/CurrentJsonDataFullWeatherPanel",
data: "{}",
dataType: "jsonp",
dataFilter: function(data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function(msg) {
// This will now output the same thing
// across any current version of .NET.
alert(msg);
},
error: function (result) {
alert('Failed: ' + result.status + ' ' + result.statusText);
}
});
});
My JSON output in Firebug shows like this.
{"d":"[{\"AirTemperature\":\"57.3\",\"BarometricPressure\":\"30.08\",\"CurrentRainRate\":\"\",\"DewPointTemperature\":\"30.7\",\"HeatIndex\":\"57.3\",\"HourlyRainAmount\":\"0.00\",\"LocalObservationTime\":\"10/14/2011 11:16:07 AM\",\"MonthlyRainAmount\":\"\",\"RelativeHumidity\":\"36\",\"SnowDepth\":\"0.0\",\"SolarRadiation\":\"\",\"SunRise\":\"7:09 AM\",\"SunSet\":\"6:22 PM\",\"TodayRainAmount\":\"0.00\",\"Visibility\":\"6561\",\"WindChill\":\"57.3\",\"WindDirection\":\"2\",\"WindGust\":\"11.4\",\"WindGustDirection\":\"92\",\"WindSpeed\":\"4.9\",\"YearlyRainAmount\":\"22.24\",\"StationTime\":\"10/14/2011 11:15:24 AM\"}]"}
Any suggestions?
Do I need to use a different way than jQuery to consume my JSON?
I should add that my fail alert is sending back 200 success but hitting the error.
Help is much appreciated. Thanks in advance.
Replace eval('(' + data + ')'); with $.parseJSON(data)
Docs: http://api.jquery.com/jQuery.parseJSON/

Posting JSON with JQuery

Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson