Data at the root level is invalid on $.ajax call - javascript

I have a simple web service that I am trying to utilize. Obviously, this will be more enahnced down the road but am trying to grasp the basic concept of the ajax call.
Web Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Tools
{
/// <summary>
/// Summary description for CFServices1
/// </summary>
[WebService(Namespace = "http://localhost:51342/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class CFServices1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hellow World";
}
}
}
JavaScript
$.ajax({
type: "POST",
url: "CFServices.asmx?/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (response) {
console.log(response);
}
});
The ajax call appears to work fine as it returns an error:
"<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>"
I have tried a couple different things that lead me down the path of the URL property being invalid but since I'm getting an actual response, I'm assuming it's correct. It definitely renders if I navigate to it through a browser. Even if I try and invoke the web service through the asmx page, it all works.
I have tried changing the data type to be plain text but that doesn't work either. Since all the web method does is reutnr the string 'Hellow World', I shouldn't need to pass any arguments but tried passing blank values just in case. Everything either brings me back to the response returning 'undefined', the html markup for the asmx page or this. The 'data at the root element is invalid.' This tells me that either the data being sent to, or recieved from the web service is incorrect or doesn't have the right formatting. This is where I'm getting hung up at because I can't figure out what could possibly be wrong here.
Although this is something probably simple, I'm not finding any luck whatsoever on SOF or other threads. Any helpful insight is greatly appreciated.

As we are calling it from jquery ie., from script part you need to make the below changes to Webservice part,
[System.Web.Script.Services.ScriptService] // Mark it for accessing from script
public class CFServices1 : System.Web.Services.WebService
We need to set script method attribute for the web method as below
[WebMethod]
[ScriptMethod]
public string HelloWorld()
Then while calling it from ajax call just remove ? in url part as below,
$.ajax({
type: "POST",
url: "CFServices.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (response) {
console.log(response);
}});
Hope it helps.

I had everything thilsiva suggested but was still receiving this error. It worked on my local development machine but not when deployed. The problem was I was getting my URL from the config file and I was accidentally missing the method name in my deployed version. So make sure you have the method name included if you're in the same situation.
url: "CFServices.asmx/HelloWorld",
not
url: "CFServices.asmx",

Related

How can I test my web api Post Web method to know what's going on inside?

So here's my situation...
We have an on-prem installation of Microsoft Dynamics CRM and I am trying to make an ajax call from it to a service I created on another one of our servers. There have been many issues already that I've solved - but I'm able at this point to successfully make a GET request to my service from CRM via javascript I've put on a form in CRM.
Just for reference (because I'm not entirely sure at this point if these things are related or not)...
I had to set anonymous authentication in IIS for my service (CRM has
its own authentication that I will be relying on)
I had to set a response header of Access-Control-Allow-Origin with the host address of our CRM installation
So, after doing those things I was able to successfully call my web service via GET. I could return back a string I had from a [HttpGet] web method.
But, now I need to actually call a web method via POST to post some data to my web service. So, below you can see my implementation for the service as well as the javascript I'm using the make the POST call.
using CRMService.Models;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Http;
namespace CRMService.Controllers
{
public class DefaultController : ApiController
{
// GET: Default
public string Get()
{
return "Hi";
}
[HttpPost]
public string GiveParameters(TestClass tc)
{
try
{
Dictionary<string, object> Parameters = new Dictionary<string, object>();
Parameters.Add("id", tc.id);
Parameters.Add("one", tc.one);
Parameters.Add("two", tc.two);
NonQuery("InsertTestItem", ConfigurationManager.ConnectionStrings["TestConnection"].ToString(), Parameters);
return "success";
}
catch (Exception ex)
{
return "ex";
}
}
}
}
var new_budget = Xrm.Page.data.entity.attributes.get("new_budget").getValue();
var new_name = Xrm.Page.data.entity.attributes.get("new_name").getValue();
var id = Xrm.Page.data.entity.getId();
data = '{"TestClass":{"one":"' + new_name + '", "two":"'+ new_budget +'", "id":"'+ id +'"}}'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://<hiddingMyUrl>/api/Default/GiveParameters",
data: data,
dataType: "json",
success: function(data) {
console.log("Success");
},
error: function(result) {
console.log("Error");
}
});
When I make this POST call, at first I could see it was doing some "preflight" stuff and making an OPTIONS request - then returning a 403 (I think, if memory serves me right). I looked that up and solved that issue by adding a Access-Control-Allow-Headers header to my web service in IIS with the value of Origin, X-Requested-With, Content-Type, Accept
After doing that my POST actually gives a 200 status code - but, as you can see in my code, I should then be seeing data in a database if everything went well.
..So of course then the question is... is my web service code working properly? And normally I could test for that easily - however I am fairly new to web api. I don't really get the best way to testing at this point - and I don't know if it's something with my code specifically or if there is some configuration issue with web api itself.
Here is my routeconfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
You should try working with a REST client.
Here are two nice ones :
Advanced Rest Client
Postman
I personally prefer Postman but really both are good.

Spring web service problems returning JSON after enabling CORS on Apache Tomcat

I have an Apache Tomcat webserver running on Windows Server 2012
I have a Spring based RESTful web service:
#RestController
public class MyController {
#RequestMapping("/myMethod")
public String myMethod(#RequestParam(value="input") String input) throws JSONException{
JSONObject joResult = new JSONObject();
joResult.put("status", "success");
return joResult.toString();
}
}
Its compiled into a war file and sitting on a web server.
I tried accessing it via Ajax from javascript as follows:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
url: "http://myserver:8080/myService/myMethod/?input=myInput",
success: function(msg) {
console.log("EXCELLENT!");
},
error: function(msg) {
console.log("say what?");
}
})
I got errors accessing this so I added the following to web.xml:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
That took care of my access error. I was able to verify the service fulfilled the request (it goes and mucks with a database and I was able to query the db and see the change).
The problem is what gets returned.
The error callback in my javascript is executed. When I print out what is returned, I get:
{“readyState”:4,“status”:200,“statusText”:“success”}
which hardly looks like an error to me.
Just for laughs, I tried changing the ajax call to
dataType: text
which resulted in an uglier error being returned even though the action was again completed successfully in the database.
Research indicates there is some kind of disconnect due to #RestController causing Spring to automagically convert whatever it returns to JSON so I changed myMethod to:
#RequestMapping("/myMethod")
public JSOObject myMethod(#RequestParam(value="input") String input) throws JSONException{
JSONObject joResult = new JSONObject();
joResult.put("status", "success");
return joResult;
}
which resulted in another undecipherable result.
So, the question is, what do I have to do to return JSON to javascript via an ajax call to a Spring based RESTful web service whose controller is annotated with #RestController?

WebMethod not working in ASP.Net Web Role (Web Forms)?

Repro:
Open VS2013, File > New "Azure Cloud Service" Project > Add an "ASP.NET Web Role" (named as WebRole1)
Select "Web Forms" template for the web role.
Add jquery-1.11.1.min.js and a new WebForm1.aspx to the WebRole1 Project.
Add the following code to the of WebForm1.aspx
<script src="jquery-1.11.1.min.js"></script>
<script>
$(function() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/Foo",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{a: 'webmethod!'}",
success: function(data) {
alert(data.d);
},
error: function() {
alert("error");
}
});
});
Add the following function to the WebForm1 class in WebForm1.aspx.cs
[WebMethod()]
public static string Foo(string a)
{
return a;
}
Set WebRole1 project as Startup Project and run. The browser alerts "undefined".
But you can get "webmethod!" using plain ASP.NET WebForm project. What is wrong?
I noticed that in url: "WebForm1.aspx/Foo": if you change the aspx part, the ajax fails; if you change the Foo part to whatever value, the ajax always succeed. This is unusual! In plain ASP.NET Web Form application, changing either part will result in "error"!
If you create an Empty ASP.NET Web Role, the ajax will succeed!!! What is going on?
JavaScriptSerializer is pretty flexible, but it might be worth trying valid JSON in the data parameter, like:
data: '{"a": "webmethod!"}'
I believe JSS will handle keys/values in single quotes, even though that's not technically valid JSON, but the unquoted a might be a bit much.

Calling an MVC Controller Action from a Javascript ajax function within an aspx page

I have a situation where I need to call an MVC controller action from a javascript file. However, the project is a WebForms project.
When running the request locally, everything works fine.
After it's deployed to a web server, it doesn't work.
You can see the image that I have where it works locally, but not on the web server.
I was somehow trying to make the action call using the Razor "#Url.Action" call, but it seems I can't put any Razor calls into the JS since it's not an MVC project.
I was trying another methodology with "<%= Html.Action", but got a server "Bad Request" with that.
How can I make this call successfully when deployed on a web server?
Here is the Controller I am trying to call.
public class ReversePenalizeController : Controller
{
[HttpPost]
public JsonResult GetReversePenalizeDataAsync()
Here is the JS Ajax call. Note that the commented out url line works fine locally, but gives me a "not found" on a web server. Note that the url line that is there now gives me a "bad request"
function getReversePenalizeData(parms)
{
var serviceBase = '/ReversePenalize/'
$.ajax({
//url: serviceBase + 'GetReversePenalizeDataAsync',
url: '<%= Html.Action("GetReversePenalizeDataAsync", "ReversePenalize") %>',
data: JSON.stringify(parms),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data, textStatus)
/// <returns>JsonResult - Grid data</returns>
[HttpPost]
public JsonResult GetReversePenalizeDataAsync()

ASP.Net web service always return XML not JSON

Currenly i use asp.net web service but when i call web service method by ajax call it always return XML not json
i try
ASP.Net web service won't return JSON - Always XML
but its also not work for me..
JS :-
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "jsonp",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
LoginWebservice.asmx :-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Demo()
{
return "Harshit";
}
where i am wrong..
jsfiddle Example:-
http://jsfiddle.net/EXvqc/
First you have to use Post method to send a request to your web service. And as you have used JSONP as it always looks for the callbacks, and you have to define callback methods for it.
Please Refer
And the other thing you have to add like following
[System.Web.Script.Services.ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class LoginWebservice : System.Web.Services.WebService
{
[WebMethod]
public string Demo()
{
return "Harshit";
}
}
Indicates that a Web service can be invoked from script. This class cannot be inherited.
Your aspx/HTML will contain
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "json",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
See output below
JSONP is not JSON, JSONP is used to get over the same origin policy (site A cannot make ajax request to site B). To solve this problem site A will create a script tag:
document.createElement("script")
Then set it's source to site B, usually specifying a callback like www.B?callback=callMe
A typical response of site B would be:
callMe({siteBSays:"hello"});
JQuery hides creating the javascript element for you so it looks like a normal ajax request. Make sure site B has the right response type headers I think it's text/javascript
Another way to do cross domain requests is that site B has a response header that allows site A making ajax requests to it (cors) by setting a response header Access-Control-Allow-Origin

Categories

Resources