Calling JavaScript function from [WebMethod] - javascript

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"
}

Related

C# function called in javascript and it's execute before the page load. why?

I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code.
i want the function to execute when i am calling it in my javascript code.
Please help me, i need this for my project in school.
i tried to use this but i didnt really understood this ->
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be
Web browser sends a request to your web server.
Web server (C# code) now handles the request and start creating HTML response.
Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
After this, your html response is sent back to web browser.
Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")
If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.

Calling a JS function from PHP

I'm making a site with several calls to PHP via AJAX, right now AJAX uses POST to get a echoed string from PHP and then compares that in a switch and then does what is required. Example in the code below
function submitPHP(dataForPHP){
//Runs ajax request
$.ajax({
type : "POST",
url : 'initPHP.php',
dataType : 'text',
data : dataForPHP,
success : function(data){
//Checks echoed data from PHP
switch(data){
case "LOGIN_ACCEPTED":
loggedInFunction();
break;
case "LOGIN_FAILED":
loggedInFailedFunction();
break;
}
}
});
}
I'm thinking if there is a way for the PHP to return what function (like "loggedInFunction();") I want to call instead of a string that I then have to compare and then call the function? I can change the AJAX to use JSON instead if that does it.
I've been looking around on other similar questions here on stack on most of them want to echo a whole function which is not what I want to do.
Thanks in advance!
I'd do this.
use HTTPS to perform login, HTTP really is insecure nowadays;
create a controller object with all allowed methods (actions);
call an action of that controller.
The idea of having a controller is convenient on several levels:
security: if a method is not in the controller you cannot call it, so it is a way to know what can be called and what is absolutely not possible to call;
cohesion: the methods are all next to each other and easier to maintain;
encapsulation: if there is any state it can be held easily inside the context of that object.
This is an example:
loginController = {
"acceptAction": function () {
},
"failAction": function () {
}
};
You can now call those methods from the AJAX handler. Say the server tells you what you must do. A verb so to speak, such as accept or fail. You can then do:
"success": function (data) {
loginController[data + "Action"]();
}
And that's it.
BTW: this is just the very basic MVC pattern. Oldie but goldie :)

How to call a specific function on a javascript file with Ajax

I have file called functionContainer.js and in that file I have written
function returnTen(){
return 10;
}
function returnName(){
return "Stack Overflow";
}
and in callAjax.js file I need to call the returnTen function and get the data via an Ajax call.
(functionContainer.js is hosted in a server)
How can I do this?
If you want to execute returnTen(); after your ajax request finishes,
then put your returnTen() function inside of a success, failure, or callback function; whichever one you choose is up to you...
Here some example with ExtJs Ajaxcall :
Ext.Ajax.request({
url: 'page.php',
params: {
id: 1
},
// scope: this,
// you can set the scope too
callback: function(opt,success,respon){
**returnTen();**
}
});
To make this method (returnTen()) callable from the client side script we need to make this static and decorate/adorn it with a WebMethod attribute.
The first thing that we need to do to be able to call the server side methods is to make the EnablePageMethods="true" in the ScriptManager control.
In Your script you can call server side js function like this:
function CallServerMethod()
{
// call the server side method here
PageMethods.returnTen();
}

Call ASP.NET web service method from 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);

Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?

I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.

Categories