Call ASP.NET web service method from JavaScript - javascript

I have the web service:
[WebMethod]
public void SendMail(string _name, string _email, string _message)
{
//Create Mail Message Object with content that you want to send with mail.
MailMessage MyMailMessage = new MailMessage("gglebati#example.com", "gglebati#example.com", "This is the mail subject", "Just wanted to say Hello");
MyMailMessage.IsBodyHtml = false;
//Proper Authentication Details need to be passed when sending email from gmail
NetworkCredential mailAuthentication = new NetworkCredential("myxxxxx#gmail.com", "xxxxxxxxx");
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
}
and i have a html page. How can i call this function from my html page? (This function must send the message to email)

Use jQuery library. It makes ajax calls piece a cake. Then follow these items:
Add an HTML button to your page, so that people can start the ajax process by clicking it
Use jQuery to hook into the click event of that button (or span, or a div, or anything else)
Make sure you have ScriptService attribute on your web service (this attribute means that you can call your service from JavaScript)
Send items to your web service method
$('#buttonId').click(function(){
// Validating input
$.ajax({
type: 'POST',
url: '/your-web-service-path.asmx/your-method-name',
data: {}
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(r){},
error: function(e){}
});
});
Just note that you have to make a JSON object out of your parameters and the name of the JSON properties should match the name of the web service parameters. Also note that the return value of the web service would be available to you as r.d object passed to success callback of ajax call.

If it's an aspx page, you can add a ScriptManager with EnablePageMethods="true"attribute, and then call PageMethods.sendMail(name, email, message, onSuccess, onFail);

Maybe you want to take a look at jQuery's ajax capabilities.

You need to do something very important: Add the ScriptService attribute the class so that it can be called from a Javascript as in this example:
[ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
// ...
}
http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute.aspx

You have to pass the three parameters from the cs code page, by calling like this way,
service.SendMail(name, email, message);

Related

Passing a javascript variable in Ajax to a Java class

I am passing a javscript variable to a java class. I am not sure if this is consider a proper way, if so is my syntax correct and how can i make sure that the variable has passed successfully to my java class?
var key = record.getKey();
$.ajax({
type: "POST",
url: "apps/APP/src/Test.java",
data: {id : key},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
A simple Java Class cannot handle an Ajax request (or any web request for that matter) You should be having a Java Web application/ Dynamic Web Application, either written with vanilla Servlets and JSP or using any frameworks like spring to handle web requests.This application must be deployed on a Servlet Container like Tomcat or Jetty.
This tutorial should get you started as its too broad to be covered in a SO answer. Do get back with a new question if you face any issues.
Updated as per your comment:
Since you have a Dynamic Web Application It should have a Servlet, and as your Ajax request is using POST method, override the doPost() and get the data from request object. Note: Use POST only if you are mutating some data in the backend else use GET.
Please see the below code.
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
request.getParameter("id"); //use the key of the json data you need
}
}

Calling JavaScript function from [WebMethod]

I need to call a JavaScript function that shows a Bootstrap modal. I have the following code:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void execModal(string groupname, int zw) {
//need to generate the data first
StringBuilder sb = new StringBuilder();
Generate gen = new Generate();
sb = gen.generateDeeperTable(zw, groupname);
//insert into my placeholder
//Append the HTML string to Placeholder.
fillPH(sb);
//run javascript function <showModel> to show the modal
}
Here is how I call the execModal method form JS:
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
</script>
The function execModal is called from a javascript function in the .aspx site.
How can I call the javascript function showModal?
Your execModal method is on the server. You have not specified where you want to invoke (call) it from, but since you've decorated it (added attributes to the method defining it...) as a WebMethod, chances are you're trying to invoke it from a (HTML) page running in a client's browser. To make this call you need a line of communication between the client that wants to run the method, and the server that holds the method. You will also notice that execModal is defined as a static method. That means that when it is invoked it will not have the instance members of the Page class, including things like fillPH (unless fillPH is static). I don't know if you're working with ASP.NET WebForms (trying to make the call from an .aspx page), or this is a service consumed by some application (method resides in an .asmx), or I guess this could even be ASP.NET MVC.
Assuming ASP.NET WebForms
Let's deal with the simplest case since there have been almost no details provided. If we assume that this method, execModal, lives in an .aspx.cs file, and you're trying to call it from the corresponding .aspx page, and this is part of an ASP.NET WebForms application...
You need to initiate the call to execModal. This requires an AJAX call from your client to your server. You can create your own AJAX framework, but there are many open source frameworks available. I will give an example below using jQuery.
You need to do the work on the server statically, or you need to use the HttpCurrent.Context to get the instance of the Page, Session, etc. The Page can be retrieved via the HttpCurrent.Context.Handler as Page.
Once the method finishes on the server, the result (success or failure), and optionally any data you want to return to the client, is sent back to the client's browser. The client portion of the application should be able to process this response with an event handler. The event handler should be associated with the XMLHttpRequest object's onreadystatechange event and process the response when the state changes to 4 (done). Frameworks, like jQuery, take care of this overhead by providing parameters in your AJAX call to specify the success/failure callbacks. Do not confuse the result (sucess/failure) of this communication process with the result of your application's processes (actual work of execModal).
Your client side (success) callback function would then just call your desired js function showModal.
Your client side AJAX call (if you were to use jQuery) would look something like this...
$.ajax({
type: "POST",
url: "Default.aspx/execModal",
data: '{groupname: "' + groupname + '", zw: ' + zw + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
showModal();
},
failure: function(response) {
alert("AJAX request failed");
}
});
This is a very basic example. You might want the server to decide what happens on success, but returning a JSON data, or a string with the name of a js function that can be executed on the client - these are just examples to get your thinking about what is possible.
Edit - account for OP's addition of PageMethods.execModal() to question
You say you're calling your server code from this...
<script type="text/javascript>
function callGenDeeperTable(zw, groupname) {
PageMethods.execModal(groupname, zw);
}
That implies that you're using ASP.NET's ScriptManager with EnablePageMethods=true. Is that correct?
That would inject the script with the PageMethods type, and define functions for each of your WebMethods. So you are using an AJAX framework - the one provided by MS. All that work of making the AJAX call is being hidden from you with PageMethods.execModal(groupname, zw). However, each of the functions generated for you (on the PageMethod object) take additional parameters for OnSuccess and OnFailure callbacks. Here is a SO answer detailing how to use the ScriptManager's PageMethod object.
The signature for any function generated on the PageMethod object corresponding to a WebMethod is...
function foo(param1, param2, param3, etc., OnSuccess, OnFailure)
In your case, you have two parameters being passed to the WebMethod, so after those two parameters you would want to supply callback functions for success and failure. showModal would be your success handler probably...
PageMethods.execModal(groupname, zw, showModal, function() { alert('failed!') });
this is what i did and worked like charm
javascript part
function buyproduct(productId)
{
PageMethods.checkifvalid(productid, OnSuccess);
}
function OnSuccess(response, userContext, methodName)
{
this[response]();
}
function functionToCallAfterwebmethod()
{
alert("Javascript Function called successfully!!");
}
Aspx.cs part
[System.Web.Services.WebMethod]
public static string checkifvalid(int productId)
{
--your any logic to check
-- pass the javascript function as return parameter
return "functionToCallAfterwebmethod"
}

Web Service method name is not valid

I get the following error "Web Service method name is not valid" when i try to call webmethod from javascript
System.InvalidOperationException: SaveBOAT Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
HTML Code :
<asp:LinkButton runat="server" ID="lnkAddBoat" OnClientClick="javascript:AddMyBoat(); return false;"></asp:LinkButton>
JS Code :
function AddMyBoat() {
var b = document.getElementById('HdnControlId').value;
jQuery.ajax({
type: "GET",
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/text",
dataType: "text",
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
C# Code (Web method in AllService.asmx file)
[WebMethod]
public static string SaveBOAT(int Pid)
{
// My Code is here
//I can put anythng here
SessionManager.MemberID = Pid;
return "";
}
I tried all solutions found on Stack Overflow and ASP.NET site.but none of them worked for me.
It was a silly mistake.
remove Static keyword from method declaration.
[WebMethod]
public string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
In my case I had copied another asmx file, but not changed the class property to the name of the new class in the asmx file itself (Right click on asmx file -> View Markup)
In my case the error was that the Web Service method was declared "private" instead of "public"
Try using this, I think datatype should be JSON
jQuery.ajax({
type: "POST", // or GET
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/json; charset=utf-8",
dataType: "json"
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
And in C# Code change Pid to string
[WebMethod]
public static string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
I too faced the similar issue. The solution includes checking everything related to ensuring all name, parameters are passed correctly as many have responded. Make sure that the web method name that we are calling in UI page is spelled correctly, the data, data types are correct and etc. In my case, I misspelled the web method name in my ajax call. It works fine once I found and corrected the name correctly.
For Ex: In .asmx class file, this is the method name "IsLeaseMentorExistWithTheSameName" but when I called from UI this is how I called:
var varURL = <%=Page.ResolveUrl("~/Main/BuildCriteria.asmx") %> + '/IsLeaseMentorExistWithSameName';
Notice that the word "The" is missing. That was a mistake and I corrected and so it worked fine.
As Sundar Rajan states, check the parameters are also correct. My instance of this error was because I had failed to pass any parameters (as a body in a POST request) and the asmx web method was expecting a named parameter, because of this the binding logic failed to match up the request to the method name, even though the name itself is actually correct.
[WebMethod]
public object MyWebMethod(object parameter)
If there is no parameter in the body of the request then you will get this error.
Did U add ServiceReference Class. Check this once. Based on your comment I can tell what to do
I had this issue because my soap method had a List<string> parameter. Couldn't figure out a way to make it work with the array parameter; so just converted the parameter to a &-delimited string (e.g. val1&val2&val3) and converted the parameter to an array in the service method.
In my case, one of the WebService receiving parameters was called aId. When I called it from javascript, I was sending the correct Id value, but the name of the sent variable was incorrectly called bId. So I just had to rename the WebService call, keep the correct value like before, and just change the variable name.

check email id already exists in database when losing focus

I want to check the entered email id already exists in my database or not. For that I need the Text box lost focus event so that I can call it in update panel trigger asynchronously. whereas in my event I can check whether the entered value exists in database or not.
I tried:
txtEmailId.Attributes.Add("onblur", "javascript:CheckEmailIdIsExist()");
If so, the what should be inside CheckEmailIdIsExist() javascript method? how to check database values asynchronously from javascript function?
look at using jQuery to make an AJAX call to a WebMethod on your site:
function CheckEmailIdIsExist(args) {
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
$.ajax({
type: "POST",
url: loc + "/" + IsUniqueEmailAddress,
data: "{" + args + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
fail: onFail
});
}
This would be on your server:
[WebMethod]
public static bool IsUniqueEmailAddress(string emailAddress)
{
// do some processing here
return true;
}
I think you will need to modify how you call the JavaScript function because you will need to pass the value of the control onblur="javascript:CheckEmailIdIsExist(this.value);"
Either use a javascript web service proxy, by adding a ServiceReference to your ScriptManager
http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx
Alternatively use JQuery's ajax method:
http://api.jquery.com/jQuery.ajax/
The URL parameter can just be an httphandler, which takes the email address as a querystring parameter, checks the database and returns a result
Well, you should create an XMLRequest to some script which should reside on the server-side. The script itself should return some value and based on it you can make a decision whether the "emailId" exists within your database or not.
Note, that the XMLRequest is the method used for ajax calls. From this point I think you should read about ajax. If you use some library (ex jQuery) it might have it built in, so it will be very easy and straight forward for you to make some working implementation and verify your data :)

MongoDB C# and how to update from Client Side using javascript

I lovely update a document with values(Maps coord) from clienside (under privileges). MongoDB use javascript in some internals functions and for MapReduce but is not clear for me if i can use client side scripts to update my repository with values. I searching to pass values from client side to an updater Db.Repository.Updater(item). It's possible to make this using javascript or need a webservice or a rest function.
Can some expert clarify this point and suggest the way.
Many thanks.
There is http interface in mongodb, so you can send direct update request to mongodb through $.ajax for example, or you can send ajax requests to yours handlers/pages/controllers and use mongo-csharp driver as usual for updates. Make your choise...
Include jquery at page first. In 'Update' button click handler paste code like this(to send ajax request):
$.ajax({
type: "POST",
url: "SomePage.aspx",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
In page(but it seems to me that better to use http hadlers ajax handling):
public void Page_Load(object sender, EventArgs e)
{
var name = HttpContext.Current.Request["name"];
var location = HttpContext.Current.Request["location"];
var item = new Item(){Name = name, Location = location};
//here update or insert your item, do what you want
Db.Repository.Updater(item)
}

Categories