I am trying to call an ASMX method from jQuery without success. Following is my code, and I don't understand what I am missing.
File Something.js,
function setQuestion() {
$.ajax({
type: "POST",
data: "{}",
dataType: "json",
url: "http: //localhost/BoATransformation/Survey.asmx/GetSurvey",
contentType: "application/json; charset=utf-8",
success: onSuccess
});
}
function onSuccess(msg) {
$("#questionCxt").append(msg);
}
File SomethingElse.cs,
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {
public Survey () {
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
}
One thing that stands out is you have UseHttpGet=true but in your jQuery code you are using POST.
Also here is a test page I created calling an ASMX page.
[WebMethod]
public Catalog[] GetCatalog()
{
Catalog[] catalog = new Catalog[1];
Catalog cat = new Catalog();
cat.Author = "Jim";
cat.BookName ="His Book";
catalog.SetValue(cat, 0);
return catalog;
}
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "default.asmx/GetCatalog",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: handleHtml,
error: ajaxFailed
});
});
function handleHtml(data, status) {
for (var count in data.d) {
alert(data.d[count].Author);
alert(data.d[count].BookName);
}
}
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
</script>
You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
I came across this question and had the same issue. I solved it by adding:
[WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]
Below your web method attribute, if you'd like to use POST. ie:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {
public Survey () {
}
[WebMethod]
[WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]
[ScriptMethod(UseHttpGet = true)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
}
Here is an example of a jQuery call to a page method on an aspx, but it would be similar to an asmx page.
$.ajax(
{
type: "POST",
url: "NDQA.aspx/ValidateRoleName",
data: '{"roleName":"' + $('[id$=RoleNameTextBox]').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ValidateSuccess,
error: ValidateError
});
I would also suggest removing UseHttpGet as Jim Scott suggested.
You can add the following to your options and check the objXMLHttpRequest to see a more detailed error response.
error: function(objXMLHttpRequest, textStatus, errorThrown) {
debugger;
}
You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:
If you read that article then you would see that it is safe to use UseHttpGet as ASP.NET has features to block the cross site scripting attack vector.
There are plenty of valid reasons to use GET.
He can remove the data parameter and change POST to GET to make the call work. Assuming you want a JSON response it would be required to add ResponseFormat=ResponseFormat.Json as well.
The following Steps solved my problem, hope it helps some one,
To allow this Web Service to be called from script, using ASP.NET AJAX, include the following line above your asmx service class for example
[System.Web.Script.Services.ScriptService]
public class GetData : System.Web.Services.WebService
{
Add protocols under system.web in web.config, please click on the link if you are not able to view configuration
https://pastebin.com/CbhjsXZj
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
If you try chrome browser, try internet explorer it worked for me and also it is about chrome browser you must add extension to works in chrome but i dont know the name of extension
Related
I have a problem with the following ajax request, which worked fine bevor, but on another virtual machine. Because of simplicity reasons, I keep the example simple.
This is my asmx-WebService with GetData method:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
class CpmService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public object GetData(string WebId)
{ return new{Result = result}; }
}
and the AJAX request:
$.ajax({
type: "POST",
url: serviceURL + "/GetData",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: '{"":""}', //'{"WebId":"' + curWeb.get_id() +'"}',
success: doFirst,
error: doSecond
});
Only the error handler doSecond is executed, but never the doFirst method. And the error message is:
{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}
What I tried(without success):
reformat the data parameter of the AJAX request '{"":""}', or {"WebId":"' + curWeb.get_id() +'"}', or "", or "{}", etc.
remove the UseHttpGet = false attribute from the web service method GetData
search for solution in Stackoverflow
I'm trying to do an ajax post to c#. When I do the post though, it results in a 404 error. Here's my code:
Javascript:
var submitParams = {
'companyName': $("#company_name").val(),
'companyAddress1': $("#company_address_1").val()
};
$.ajax({
type: "POST",
url: "ClientManagement.aspx/Submit",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify({ submitParams }),
success: function () {
alert("hi");
$(this).dialog("close");
},
error: function (e) {
debugger;
}
});
c# code:
[WebMethod]
public static void Submit(object parameters)
{
string name = parameters.ToString();
}
So it can't find my ClientManagement.aspx/Submit method. It jumps straight into my "error" function. Also, this is being performed on a regular aspx page.
Any idea what I'm doing wrong?
Could it be as simple as
url: "/ClientManagement.aspx/Submit"
?
Usually, ASP.NET Web Services have a .asmx file extension. If that does not work, try using the fully qualified domain name of the web service.
After a day of trying to resolve this, I came to the head shaking realization that I misspelled my page name. In my ajax post, I'm calling ClientManagement.aspx. My real page was misspelled as ClientManagment.aspx (missing the 'e').
Thanks for your help.
I don't get why $.ajax() function cannot reach my [WebMethod].
Here is the jQuery below:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Here is the C# code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string UpdateAsyncBasket(string name)
{
// random stuff
return "Received : \t " + name;
}
When I place a breakpoint on the return statement I never seem to get there.
What am I doing wrong?
Based on the experience I've had with this stuff, I THINK the JS has to be put inside inside .NET's page load javascript function to access C# web methods.
function pageLoad(sender, eventArgs) { }
Try a GET instead of a POST. I have a few web methods that work fine using similar javascript, but have decorated the method with this instead of just [WebMethod]:
[WebMethod, ScriptMethod(UseHttpGet = true)]
And then make sure your ajax call specifies GET:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Try this code,
$(document).on("click",".BasketUpdaterSubmit",function(){
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
});
And the web.config you have to add following section inside the system.web section
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Above code should work(tested in my machine). My best suggestion for you is create a web service for this. so you can omit the page life cycle.
You can refer following sample to learn how to do it properly
http://tutorials.cmsnsoftware.com/2011/01/how-to-call-csharp-function-in-ajax.html
We figured out what's going on.
It seems that there is a default ajax setup function which was interfering with my jquery function and didn't proceed when testing. Most probable reason is improper parameter handling.
Sorry for the late response. Thank you all.
i'm tried to implement ajax using jQuery.Its my first time to use ajax.so in a button click i need to display the current datetime. For this, i write the below code
//==============aspx page===============
<script type="text/javascript">
$(document).ready(function (){
var Button1 = $("#Button1");
var Label1 = $("#Label1");
Button1.click(function (){
$.ajax({
type: "POST",
url: "/myownajax14/WebService/WebService1.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Label1").text(msg.d);
//alert('hi');
},
error:alert('error');
});
});
});
//================asmx.cs page===========
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetDateTime()
{
return DateTime.Now.ToString();
}
}
My problem is,it doesn't give the answer..and it doesn't show any error.Have any mistake in this code?Please help me..
I too had a similar problem it's simple try this:
You need to specify type="button" attribute.
contentType: "application/json;" means that the client need the server to response a json type data.But the server response a string type one instead.
In the "success" block,the "msg" must be like '2010-10-10',so error happens in msg.d.
try the following for a string type data,or response a json type data in the server code such as {"y":2010,"m":10,"d":10}.
contentType: "application/text; charset=utf-8",
success: function (date) {
$("#Label1").text(date);
}
Have you tried accessing the ASMX directly using a browser? This way, you can easily see what kind of response your ASMX is producing...
I am trying to create a webservice that takes data, posts it to a database, and returns the result. I know how to write all the C# code that does that, but it is the communication that I am having problems with. At the moment, I am just trying to invoke the service and get back "Hello World" (I start with something simple since I have no idea what I'm doing)...
My Jquery:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert("Success");
$("#log").html(msg);
alert(msg);
}
});
My Webservice:
public class PersonService : System.Web.Services.WebService
{
~
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
~
}
After using chrome to Inspect the Element, and selecting the Network tab, finding my webservice, it shows me that the result was:
<?xml version="1.0" encoding="utf-8"?>
<string>Hello World</string>
So, it seems that the service executed successfully, but the success function does not fire, and there are no errors in the console. What is going on? Also, why is the result in XML?
Do I need to use Web Services, or could I just post the variables via AJAX to an ASPX page that would process it the same way it would a form submission?
Using jQuery to Consume ASP.NET JSON Web Services ยป Encosia
$(document).ready(function() {
$.ajax({
type: "POST",
url: "RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Hide the fake progress indicator graphic.
$('#RSSContent').removeClass('loading');
// Insert the returned HTML into the <div>.
$('#RSSContent').html(msg.d);
}
});
});
Also, you're missing [ScriptMethod] on your web service method and [ScriptService] on your service class.
[WebService]
[ScriptService]
public class PersonService : WebService
{
[ScriptMethod]
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
}