Web Service Ajax Returning HTML - ajax

Hey all i am trying to figure out why i can not get any returned HTML from my web service.
This is my javascript that calls out to the WS:
function getTVGuide(whatsBeingSent) {
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
async : true,
type: "POST",
url: "http://192.168.9.7/Service.asmx/getTVGuideData",
data: '',
contentType: "application/json",
dataType: "json",
success: OnSuccessCallTVGuide,
error: OnErrorCallTVGuide
});
}
function OnSuccessCallTVGuide(response) {
console.log(response.d);
}
function OnErrorCallTVGuide(response) {
console.log('ERROR: ' + response.status + " " + response.statusText);
}
And the WS is this:
<WebMethod()> Public Function getTVGuideData() As String
Try
Dim sr As StreamReader = New StreamReader("c:\tvlistings.html")
Dim line As String = ""
line = sr.ReadToEnd()
sr.Close()
Return "done"
Catch Ex As Exception
Return "err" 'Ex.Message
End Try
End Function
That works just fine if i only return something like "DONE".
However, if i try returning line then it no longer works. Giving the error:
ERROR: 500 Internal Server Error
I've tried chanign the return values in AJAX to:
contentType: "application/html",
dataType: "html",
and also
contentType: "application/text",
dataType: "text",
But i still get the same error...
What could i be doing incorrect?

ERROR: 500 Internal Server Error means that there's some internal exception in service. You may be getting HTML contents due to CustomError ON and customError module returning a HTML page configured in IIS. CustomError module will change Content-type to text/HTML.
HTH,
Amit

Related

My Ajax POST is coming up as an error even though I am returning 200

I am making an AJAX post to a Jersey Resource. I build an image and return it. The issue is, no matter what status I return, Ajax thinks it is an error. I can actually use the error message (via error.responseTest) and it works fine. But it is ugly. What do I return to make it a success? I have returned OK(200), Accepted(202) and Created(201). All of them give me an error message but in my Console Network tab, I get a success (green with the proper status).
I am returning it like this:
return Response.status(Response.Status.ACCEPTED).entity(image).header('Content-Type',"image/png").build();
My JS code:
$.ajax( Monocle.config.Sightline.jobUrl + "/sightline", {
type: "POST",
processData: false,
data: JSON.stringify({
Lat1: Monocle.Sightline.BBOX(feature,2),
Long1: Monocle.Sightline.BBOX(feature,1),
Lat2: Monocle.Sightline.BBOX(feature,4),
Long2: Monocle.Sightline.BBOX(feature,3),
OrgLat:observerCoords[0].lat,
OrgLong:observerCoords[0].lon,
ObHeight: feature.attributes.observerHeight,
TargHeight: feature.attributes.targetHeight,
OuterRadius: feature.attributes.outerRadius,
LVA: feature.attributes.lowerVertAngle,
UVA: feature.attributes.upperVertAngle,
sAzimuth: feature.attributes.startAzimuth,
eAzimuth: feature.attributes.endAzimuth,
outputType: "MAX"
}),
contentType: "application/json",
dataType: "json",
success: function( results ){
var graphic = new OpenLayers.Layer.Image(
Monocle.currentWidget.name + " Destination " + featurenum,
"data:image/png;base64," + results,
new OpenLayers.Bounds(Monocle.Sightline.BBOX(feature,1), Monocle.Sightline.BBOX(feature,2), Monocle.Sightline.BBOX(feature,3),Monocle.Sightline.BBOX(feature,4)),
new OpenLayers.Size(580, 288),
{ isBaseLayer: false,
opacity: 0.3,
displayOutsideMaxExtent: true
});
feature.legionObject = graphic;
graphic.relatedlayer = Monocle.currentWidget.name + " Destination " + featurenum;
Monocle.Map.map.addLayer(graphic);
},
error: function(errMsg) {
// TODO: really handle any errors
}
});
Setting dataType: "json", means that your response is to be json which it isn't that would cause the error so just remove it.
Also is your image data has to be base64 encoded to make a data uri.

Ajax Call with PUT method

i am trying to make ajax call with PUT method. Below is the code, but i am getting with the error XML Parsing Error: no element found Location: moz-nullprincipal:{c847a4af-f009-4907-a103-50874fcbbe35} Line Number 1, Column 1:
$.ajax({
type: "PUT",
async: true,
url: "http://localhost:8080/karthick/update",
data: JSON.stringify(params),
contentType: "application/json",
dataType: "JSON",
processdata: true,
success: function (json) { //On Successfull service call
},
error: function (xhr) {
alert(xhr.responseText);
}
});
return false;
};
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
But this service is working Good with Rest-client jar. Also my POST method works fine in my browser. Please help me in this.
Regards
Karthick
Usually, this error comes, when making a cross browser request. Try data: JSONP and see if it helps.

How To Use Object Returned By VB.NET Web Service

I have a Javascript function that passes a string into a VB.NET Web Method. Here is the Javascript
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + e);
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial
Here is the VB.NET web Method. The Web Method simply takes the string and sends it back to the Javascript:
<WebMethod( )> _
Public Function testWebService(str As String) As String
Return str
End Function
When the Web Method returns successfully my AJAX block returns the following message:
"It worked: [object Object]"
So my question is, how do I use the returned object? The object should be a string containing the words "hello world" but how do I access the string value?
ASP.Net WebMethods wrap their return values in a JSON object with a d property. (You can see this in the response body in the browser's developer tools)
You need to write e.d to get the actual value.
if you do:
$(e).text()
You'll get your text;
So change this to be:
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + $(e).text());
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial

Resource interpreted as Script but transferred with MIME type text/xml

In VS 2010 i have two projects,one for webservice and another for asp.net pages.
i try to call a webservice (from the .js of an asp.net page) like this:
var host = "localhost:15932";
var url = "http://" + host + "/MyWebService.asmx/GetFeed?callback=?";
$.ajax({
async: true,
type: 'Get',
url: url,
data:{ CountryId: CountryId, FeedDateString: FeedDateString, Previous: Previous},
contentType: 'application/json; charset=utf-8',
//contentType:'text/xml ',
processData: true,
dataType: 'jsonp',
success: function (response) {
var result= response.d;
,
error: function (request, status, error) {
alert(request.responseText);
}
,
failure: function (msg) {
alert('somethin went wrong' + msg);
}
});
the call goes wel ,but the result returned from the webservice is xml ,and chrome shows an error message:"Resource interpreted as Script but transferred with MIME type text/xml"
i get an xml stream when i type this in my browser:
"http://localhost:15932/MyWebService.asmx/GetCountryFeed?callback=jsonp1339760946308&CountryId=1&FeedDateString=&Previous=true"
the code of my webservice method:
[WebMethod(Description = "Get feed")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet=true)]
public List<Feed> GetFeed(int CountryId, string FeedDateString, bool Previous)
{
return (new UserFeedManager()).GetFeed(CountryId, FeeDate, Previous);
}
what to change to make the response.d in json format?
You need to override the web services response.
Set GetFeed's return type to void.
Serialize List.
Return the json:
HttpContext.Current.Response.ContentType = "text/javascript";
HttpContext.Current.Response.Write(json)
HttpContext.Current.Response.End();
You may want to create a class to handle your response's and pass in your functions that return json with a Func function or Func parameter.

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources