JSON, invalid label, issue consuming JSON - 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/

Related

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

jQuery $.ajax failing no error message, server responded with 200 OK

I have an ajax call that works fine locally, but when I published it into the server, the code is never executed but returns "200 OK" anyway. No "success" code is ejecuted, nor the "error" code. Here's my ajax call:
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
for (var i = 0; i < myObj.length; i++) {
var element = document.getElementById("LbItem " + myObj[i].MenuItemID);
element.innerHTML = "<b>" + element.innerHTML + " (" + myObj[i].Cantidad + ")</b>";
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I also tried to put the complete url in the "url" field but still no luck.
The weird thing is that when I put the complete url directly into the browser, it is still not executing the code. And it works fine locally!!
I know there's a similar post (jQuery $.ajax failing silently, no error messages, and server responded with 200 OK) but is not resolved and it's driving crazy here.
PD: this is NOT cross-domain, my ajax code is in a .ascx and I am trying to call a method on an .aspx
Thanks very much!!!!
EDIT: I tried to remove the System.web.extensions reference of my web project and add the dll to my bin, but it's still not working (the 1.0.61025.0 version). Besides, I am running the ASP.NET website in IIS with framework 2.0, and I don't have framework 3.5 installed on my server (but locally I do). Maybe that's the problem? I can't install it because of the client security policies, what shall I do?
EDIT 2: I tried doing a simple response from my .aspx, just to test if the problem was in that method, but it is still not executing the success function. Here's my .aspx code:
[WebMethod]
public static string ObtenerContadores()
{
return new JavaScriptSerializer().Serialize("true");
}
and adapted the .ascx
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(dictionary) {
alert("hello");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Here's your problem: "The weird thing is that when I put the complete url directly into the browser, it is still not executing the code." Your JavaScript is expecting -- requiring -- a JSON response, and is apparently getting no response at all. This is not a JavaScript problem, but a problem with your .aspx page.
EDIT: Based on your comments below, it's clear that the problem is that your .aspx page is not returning what you expect. Because the .aspx doesn't produce the expected output even when you go to it directly, the problem is in that page, not in the jQuery.
Pretend the .aspx produces {}, false, or true. Your success code will run, but not do anything. Try putting an alert("Foo"); in there and watch what happens. The problem isn't that your jQuery is busted; it's that it isn't getting meaningful input from your .aspx page.
P.S. I would recommend using a variable name other than data in your success function, just in case it's getting messed up by the data object attribute in your .ajax call.
Okay, I believe I've figured this out, so I'm posting a second answer to preserve the prior discussion.
Here's the fix. Remove this line:
contentType: "application/json; charset=utf-8",
In my test script, this caused jQuery to send the Content-Type header application/json; charset=utf-8, as expected, but the actual contents of the request were not properly sent as JSON. For example, rather than sending {"foo":"bar"}, it was sending foo=bar. As a result, the receiving script acted as if no data was posted at all. When I commented out the line above, my test script worked fine and did whatever I expected with the values received from the target URL.
Note that this will post your data as normal post data. For example, if your $.ajax() call looks like this, the posted data will contain a variable named foo and one named who:
$.ajax({
...
data: {foo : "bar",
who : "what"},
...
});
If you want to post already-serialized JSON, do it like this:
$.ajax({
...
data: { somevariablename: '{"foo":"bar","who":"what"}' },
...
});
Then, you just have to parse the POST parameter somevariablename on the server side.
Hope this helps!
If its VS2012, try for adding Mime Type Handler, since VS2012 has IIS express and it need to add Mime type handler externally,
Add below code to web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
.. and if its not VS2012 then follow this link
add .json handler support in IIS 7
I want to thank everyone for your help.
I finally had to install the 3.5 Framework on the server, I had no choice.
The second I installed it, and updated the web.config dll's references to 3.5, it worked like a charm.
Thanks again!!!!!

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

Getting invalid json primitive error in jquery-ajax

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.

Consuming broadbandmap.gov json service errors

I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).