Calling an ASP.NET server side method via jQuery - asp.net

I'm trying to call a server side method from client side via jQuery. My code is as follows:
Server side:
using System.Web.Services;
[WebMethod()]
//[ScriptMethod()]
public static void SendMessage(string subject, string message, string messageId, string pupilId)
{
//Send message
}
Client side:
$("#btnSendMessage").live("click", function(){
var subject = $("#tbSubject").val();
var message = $("#tbMessage").val();
var messageId = $("#hdnMessageId").val();
var pupilId = $("#hdnPupilId").val();
$.ajax({
type: "POST",
url: "./MessagePopup.aspx/SendMessage",
data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId),
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(textStatus);
},
success: function(result){
alert("success");
}
});
return false;
});
I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`

To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:
$.ajax({
type: "POST",
url: "MessagePopup.aspx/SendMessage",
data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Edit: The extension doesn't change to .asmx but remains .aspx.

It looks like you're trying to make use of a page method.
Take a look here Page Methods in ASP.NET Ajax for help

You should use web service instead of regular aspx web page. Web pages has no support to call web methods, I believe your jQuery request loads the HTML page instead. I suggest you two things:
Use Fiddler2 (with IE) or HttpFox (with Firefox) to debug AJAX requests and responses on client side.
Use WCF web service on the server side. in this case you can use SvcConfigEditor and SvcTraceViewer to configure and debug web methods on the server side.

$.ajax({
type: "POST",
url: "MessagePopup.aspx/SendMessage",
data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {},
error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }
});
If this doesn't work...and gives "Syntax Error: syntax error"...then add this
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
between </compilation> and </system.web> in your Web.Config file.
Hope this will help somebody because took me a while to figure that beside jquery function i have to add that in Web.Config.

Here is code that might work in your situation.
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the button.
$("#btnSubmit").click(function () {
//get the string from the textbox
$.ajax({
type: "POST",
url: "testSearch.aspx/GetMyShippingDate",
contentType: "application/json; charset=utf-8",
data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",
dataType: "json",
success: function (date) {
// Replace the div's content with the page method's return.
Success(date);
},
error: Failed
});
});
});
function Success(result) {
$("#ParcelShippingDate").html(result.d);
}
function Failed(result) {
alert(result.status + " " + result.statusText);
}
There is an example that has always work for me.
Here is the complete article http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx
It works well for those that want a straight forward way of using the jquery asp.net method call back

Related

SVC Web service consuming from code behind but not from javascript

I want to call web service in project (but in same solution) from myClient project.
I have added service reference in myClient project.
When I call scf from code behind it, works but when I try to call it from JavaScript using JSON, I am unable to do so. Guys pls help.
"http://someurl.com/MyWebService.svc/DoWork/" is path of my Service
abovive url someurl is url of localhost
This code is from a.aspx of client application of JSON,
$.ajax(
{
type: 'GET',
url: 'http://someurl.com/MyWebService.svc/DoWork/',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert(jqXHR.responseText);
},
success: function (data) {
alert(data);
}
});
From Code behind
string postData = "http://someurl.com/MyWebService.svc/DoWork/";
int timeout = 10;
//string dwml = string.Empty;
//MyServiceReference.MyWebServiceClient ms = new MyServiceReference.MyWebServiceClient();
//dwml = ms.DoWork();
//System.Net.WebClient webClient = new System.Net.WebClient();
//dwml = webClient.DownloadString(serviceURL);
//Response.Write(dwml);
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(postData);
// Set the Method property of the request to POST.
webRequest.Headers.Clear();
webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 1000 * timeout;
webRequest.PreAuthenticate = true;
webRequest.ContentType = "application / x - www - form - urlencoded";
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
webRequest.Timeout = 150000;
// Create POST data and convert it to a byte array.
WebResponse webResponse = null;
StreamReader objSR;
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
Stream objStream;
string sResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();
objStream = webResponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
//<<sResponse doesn't contain Unicode char values>>
sResponse = objSR.ReadToEnd();
Response.Write(sResponse); // OR Response.write(HttpUtility.HtmlEncode(sResponse))
Guys this immediate second question (both asked by me only) which only myself has answered or commented. I got ans 4 this from stack overflows old question
Basic example of using .ajax() with JSONP?
Issue was with cross domain web-service call is not allowed through AJAX.
I came across new concept of JSONP, wow feeling great!
But I was expecting quick reply from Stack overflows other members.
I will not be able to rescue myself every time friends!
calling WCF service from RESTclient in different solution without JSONP:
Here I came up with another working solution for, calling WCF service from RESTclient in different solution without using JSONP i.e. Enabling CORS of service (Cross Origin Resource Sharing) policy.
We all must have tried:
Adding Header Access-Control-Allow-Origin in web-config file of Service Project,
Code in web-config :
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
but anyhow, that didn't worked out for me!
So, there is another way to achieve the same, is to Create a Global.asax in Service Project and Add this code to the Global.asax.cs:
Code in Global.asax.cs :
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
And you can continue with your regular AJAX call from RESTclient solution to WCF service:
Sample AJAX :
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:51058/Service1.svc/GetData",
dataType: 'json',
success: function (data) {
//do success part here
alert(data);
},
error: function (e) {
alert(e.message);
}
});
});
The best part is, no need to do any modifications in RESTclient project solution.
here I have tried so far
SVC code file service1.svc.cs :
using System;
namespace TestConnection
{
public class Service1 : IService1
{
public string GetData()
{
return string.Format("You entered: {0}", "Success");
}
}
}
JavaScript function:
<script type="text/javascript">
$(document).ready(function () {
var text;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'Service1.svc/GetData', /*you .svc address : 'http://someurl.com/MyWebService.svc/DoWork/'*/
dataType: "json",
async: false,
success: function (a) {
var response = $.parseJSON(a);
text = response.Table[0];
alert(text);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Failure');
}
});
});
</script>
All above code you might have tried, some important note to get this worked is:
1. as WCF .svc works on Representational State Transfer (REST), you have to explicitly mention data get request in service1.svc Markup file,
[OperationContract]
[WebGet()]
//You can use below attributes to make necessary modifications
//RequestFormat = WebMessageFormat.Json,
//ResponseFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Bare,
//UriTemplate= "GetData"
//)]
string GetData();
To use WebGet,you will need to add library System.ServiceModel.Web to your service Project.
And if you have issues with basic settings then,
Web.Config:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMathService" />
</basicHttpBinding>
</bindings>
</system.serviceModel>
NOTE: This will not work for cross domain, if you want that, its answered Here.

Ajax Webservice call

I have the below code in my ASPX page to get some data from a webservice. I cannot use WCF so I am using the ASMX and .Net 3.5. However, what I get back is the yellow ASP.net error page talking about setting the web.config error tag to OFF. If I call my method from code behind and response.write it to the page I get a Json string that I have viewed in JSON Viewer and it parses fine. My issue here is the URL format. What am I doing wrong here. Every example I have found uses the webservice.asmx/Method format. I have also added the protocols to my web.config
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
Page Script:
$.ajax({
type: 'GET',
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
success: function (msg) {
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= msg.length - 1; i++) {
var row = "<tr>";
row += "<td>" + msg[i].ID + "</td>";
row += "<td>" + msg[i].Title + "</td>";
row += "</tr>";
table += row;
}
table += "</table>";
$("#myDiv").html(table);
},
complete: function () {
alert("complete");
}
});
Webservice:
<WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function MyMethod() As String
'removed for shorter post
End Function
UPDATE: So using the dev tools in Chrome I have found that part of my problem was the server was returning a 403 Forbidden error. After som tweaking I have come up with a partial solution that gives me back my data with json formatting. However, that json formatted text is now wrapped in XML. :-(
I have yet been able to figure out how to get the XML out of my json. Any ideas?
You should have
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
similar to:
contentType: "application/json",
url: '/folderonmyserver/mywebservice.asmx/MyMethod',
dataType: 'json',
data: "{}", // needed for .Net not to blow up sometimes - or send real data
and in your success: reference msg.d (or have a translation to isolate that for .Net) given your .net version
success: function (msg) {
var mydata = msg.d;
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= mydata.length - 1; i++) {

XML Parsing Error: no element found

I have an ASP.Net 4.0 Web Service method that returns a well-formed XML document. I am successfully displaying the XML in a browser locally and once deployed on the production server.
When I try to call the method via jQuery ajax I'm getting the error:
XML Parsing Error: no element found Location: moz-nullprincipal:{6c0c99b3-0fed-454f-aa6e-e0fca93a521c} Line Number 1, Column 1:
$.ajax(
{
url: 'http://mywebservice.com/WebService/Service.asmx/UserData',
type: 'GET',
contentType: "text/html; charset=utf-8",
dataType: "xml",
data: 'authorizedId=1234&authorizedUser=Test&authorizedCode=xyz',
'success': function (data) {
$('#XMLContent').html(data.responseText);
},
'error': function (xhr, status) {
alert(status);
},
'complete': function (xhr) {
}
});
I've tried changing the contentType but same results.
However, I can make the call in C# like this and I get my well-formed XML:
XmlDocument document = new XmlDocument();
document.Load("http://mywebservice.com/WebService/Service.asmx/UserData?authorizedId=1234&authorizedUser=Test&authorizedCode=xyz");
ViewData["XMLData"] = document.OuterXml;
In my web service web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Thanks...
If the web service is not on the same domain as the page, you can not use AJAX calls to fetch data from other domains.
You can create a proxy web service in your aplication which calls your external web service, then call your own proxy from AJAX/jQuery.
http://forum.jquery.com/topic/jquery-ajax-and-xml-issues-no-element-found
Hope that helps
Thanks bgs264...
Now in my aspx page:
$.ajax(
{
url: '/Home/WebService',
type: 'GET',
contentType: "text/html",
dataType: "html",
data: 'authorizedId=1234&authorizedUser=Test&authorizedCode=xyz',
'success': function (data) {
alert(data);
$('#XMLContent').html(data);
},
'error': function (xhr, status) {
alert(status);
},
'complete': function (xhr) {
}
});
In my MVC controller:
public ActionResult WebService(string authorizedId, string authorizedUser, string authorizedCode)
{
XmlDocument document = new XmlDocument();
document.Load("http://mywebservice.com/WebService/Service.asmx/UserData?authorizedId=" + authorizedId + "&authorizedUser=" + authorizedUser + "&authorizedCode=" + authorizedCode);
ViewData["XMLData"] = document.OuterXml;
return PartialView();
}

How do I persist session values in ASP.NET?

I'm implementing IHttpHandler and IRequiresSessionState and I'm using context.Session but after I set up a value in Session, it's lost in the next request. What can I do to persist the values ?
$.ajax({
url: "/test.test",
type: "POST",
data: "{'type':'GetStep'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {...}
});
The second call is similar to this, but the values that get set when I call this function are also lost on the next request.
public void ProcessRequest (HttpContext context)
{
context.Session ["Game"] = new Game (); // next time it is null
}
How do I persist values in Session state in ASP.NET ?
Do you have session state defined in your web.config? Something like this
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"/>

Authenticate windows user using jquery

MyMasterPage.master
<head runat="server">
<script type="text/javascript">
$(document).ready(function() {
var userName = '<%# System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString() %>';
alert(userName);
$.ajax({ type: "POST",
url: "DemoWebService.asmx/GetFulName",
contentType: "application/json; charset=utf-8",
dataType: "xml",
dataType: "json",
data: "{'networkId':'" + userName + "'}",
processData: false,
error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) { ajaxFinish(xml); }
});
});
</script>
</head>
Even though the userName variable is blank, I get the logged in user from my WebMethod:
[WebMethod]
public string GetFulName(string networkId)
{
//return networkId + " Full Name";
return networkId + " From Server: " + System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString();
}
Since I am checking on the master page, what is the best practice to store the authentication result so that I do not have to check on everypage. Prior to using jquery I was storing in Session.
Thanks
web.config
<authentication mode="Windows"/>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
You could store the result in a cookie, and then check that cookie on subsequent pages to get the logged in user's name. You would want to make sure and delete the cookie if the user logged out or their authenticated session expired.
There is a plugin available for jQuery to support reading/writing/deleting cookies.

Resources