AJAX: How to call javascript function from C# code behind AJAX method - javascript

I need to call a javascript function(CommentButtonShow()) from c# code behind ajax method. I am unable to achieve this.
Following is the C# ajax method,
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string CheckPassword()
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "ScriptManager1", "javascript:CommentButtonShow();", true);
}
Below is the javascript function,
function CommentButtonShow() {
$("#ctl00_mainContentPlaceHolder_divEmailFriends").removeClass('hidden').addClass('show');
}
Please help me out.
Thanks.

You can call CommentButtonShow() function in the javascript inside the ajax call success event. you cannot call javascript function inside web methods. if it is a post back your code will work but for ajax call backs it wont work.

I am answering this to shed more light for those who are new to this cilent-side and server-side scripting and mix up when doing some interesting work to them :)
This is absolutely impossible to call a Javascript (client-side) function from within C# (server-side) code. I mean, even you really cant invoke a javascript back into the server-side code in any programming language on earth!
It is very simple. Server-Side code renders the client-side code. Since the client code (html/javascript) resides in the browser you don't have any hook for javascripts at least to get it in server-side and then invoke. But for Asp.Net provides you a hook that actually transforms client-side HTML controls (most HTML tags) into server-side controls (as the .net framework supports) and then you can access their properties and some methods which only invoke at server-side. It does not mean that you have javascript events or such. Whatever you do with those server-side controls HAPPEN only at server-side and everything with that is COMPLETED before the final code of THAT control is sent to the browser to render. That is why when the html of such controls is rendered you see a typical .net based ID generation which looks like _ctr01 and such.
Anyway, using Ajax (at client-side) you can still invoke server-side methods using Ajax.Net and/or Ajaxpro (ajaxpro.info) or a custom javascript lib (jquery).
I hope this helps only in understanding what you are doing is actually NOT possible. I still would not rate your question negative as it is really going to help many new comers to understand how things work and how people who have gone through this got it right.
I hope its very fair use of this forum to provide the information that helps everybody rather negating their points without letting them know what they are asking/answering is right/wrong.
Thanks a lot.

We can call a method in codebehind from the JQuery AJAX call and depending upon the status whether it is error or success the corresponding method will be executed.
function MyMethod() {
$.ajax({
type: "POST",
url: "CodeBehind.aspx/ClearData",
contentType: "application/json;charset=utf-8",
data: '',
dataType: "json",
success: function (data, textStatus) {
closePopUpwindow1();
},
error: function (data, textStatus) {
closePopUpwindow2();
}
});}
[WebMethod]
public static void ClearData(){
Page.SetGridSessionData(gridID, null);
}
If the server side method is successfully executed then closePopUpwindow1 method is executed else closePopUpwindow2 method will be executed.

Related

Calling C# method (using PageMethod) from LinkButton without postback (MasterPage website)

I create several LinkButtons dynamically in an ASP page with MasterPage. In a separate JavaScript file, i have a JS function that changes the text of the LinkButton when clicked, i.e. "Yes" to "No" and vice-versa. It's sort of a "Like" button. So it's mandatory the page stays static when people click the LinkButton (would be annoying if not).
A C# method with parameters must be executed when the LinkButton is clicked.
I add this click property to the LinkButton, to use the method that is in a separate C# Class file:
MyLinkButton.Click += (sender, e) => { MyClass.MyClick(par1, par2); };
But the thing is, if i add the following property to prevent postback and keep the page static when LinkButton is clicked:
MyLinkButton.Attributes.Add("href", "javascript:;");
It no longer runs the MyClick method in the MyClass file.
So i tried to call the MyClick method from the JS code that does the "Yes" to "No" change on click using PageMethod.
In MyClass i added: the reference to System.Web.Services and put [WebMethod] above the public static void MyClick() method.
Also added a ScriptManager to my MasterPage file inside body/form and set the attribute EnablePageMethods="true".
The problem is, with or without the ("href", "javascript:;") attribute set on LinkButton, the PageMethod is not calling the MyClick method in the MyClass file. I tried the following two ways:
PageMethods.MyClick(par1, par2)
and
PageMethods.MyClass.MyClick(par1, par2)
And both aren't triggering the method. I appreciate any comments or suggestions.
The way a link button works is, its href points to the __doPostBack JavaScript method. This triggers a message to be sent to the server. Since you've replaced the href with javascript:, essentially "do nothing," that explains the behavior you're seeing.
If you want to send data to the server without reloading the page, you need to use AJAX. There are two main methods, one is the UpdatePanel, most people, including myself, would recommend against this model. Why? Well think of it this way, based on what you're telling me, you have a "like" button. I'd guess there are two pieces of data your server-side method needs, some ID to identify what they are liking and a Boolean to say like or not like. If you use an UpdatePanel, the entire ViewState has to roundtrip to the server. Additionally, the server will respond with the entire HTML contents of everything in the UpdatePanel. There are many good articles on the internet that go into more detail, here is one if you're interested, but I've summarized the points. If you're trying to build a lightweight, fast modern website, it's not the way to go. If you're trying to get something done quickly and don't want to write JavaScript, it might be, however JavaScript is pretty much a requirement for the modern web.
Alternatively, you can use straight AJAX. This requires you to put a method in your code behind decorated with the [WebMethod] attribute. This means it can now be called from JavaScript via AJAX. Using my example you'd have:
[WebMethod]
public static bool DoLike(string id, bool likeOrNotLike)
{
// Your implementation
}
Now, how do you call it. I'd recommend you use a framework such as jQuery to call the AJAX as it simplifies a lot of the syntax for you. With jQuery, you can simply do:
$.ajax({
type: "GET",
url: "MyPage.aspx/DoLike",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { id: "123", likeOrNotLike: true },
success: function (msg) {
alert("It was called successfully");
},
error: function () {
alert("An error occurred calling it");
}
});
The code above sends two parameters to the DoLike method, "123" (the ID), and true (likeOrNotLike). You're method will be called with these parameters as if you had called it from C#. The framework takes care of all of that.
To add jQuery to your page, simply add a:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
If you're against jQuery, I can modify my answer to use XMLHTTPRequest directly but it's more cumbersome.
As you can see, AJAX isn't magic though, you can't simply add [WebMethod] to your event handler and all will work. In fact, if you go the straight AJAX route, you're not even using an event handler, you're calling a server side method directly.
You can certainly do the UpdatePanel as some others have suggested here, it will work. It's just, in my, and many other opinions, overkill for AJAX. It was Microsoft's attempt at implementing AJAX without the developer having to do much. Just like with ViewState, it comes with a price. It's up to you if the price is tolerable.
my 2 cents: I think it's because you are trying to run server code without sending the necessary info to the server. Without postback you cant expect the server to process the event.
Not sure if there's a way to do that in ASP. Maybe you could use an AJAX call but I never used it for this specific purpose.
If you want to call the server without a postback, you have to use an UpdatePanel or a native Ajax function. In your case, I believe UpdatePanel is nicest one.
Put your fields and the button inside the UpdatePanel, then everything will work fine, just like magic.
To see how to use UpdatePanel, take a look at
https://msdn.microsoft.com/en-us/library/bb386454.aspx
https://web.archive.org/web/20211020102853/https://www.4guysfromrolla.com/articles/102407-1.aspx
http://ajax.net-tutorials.com/controls/updatepanel-control/

What is the right way for Searching functions in a Website with Javascript?

Its known that interactions between Javascript and SQL-Databases are not very secure. But most Websites use it cause the Webside doesent reload to show matches in a search.
With PHP it isn't possible to change Page-Contents without a completely Page-Refreshing.
Witch is the right way to get Data from SQL with Javascript without security-neglects.
Aspeccialy for a Searching function with directly matches in a list.
You can use 2 way to get data from db by using js;
1. Ajax:
function refresh() {
$.ajax({
url:"your url",
method: "GET",
data: your_params,
success: function(response) {
$("#specific_div_id").html(response);
}
});
}
You can do this within an interval like;
setInterval(refresh, 5000);
in order to get content in every 5 sec.
2. Websockets
In AJAX, you are requesting in every 5 secs to get updated content from server. Think that, you are not getting content server pushes updated content to you. In other words, server notifies you on any updated data. You can have a look at Socket.io for an example implementation of websockets. When server notifies you, you can take data and put it related html area
As mention in the commentaries, the best way is to use AJAX, which is an acronym that stands for Asynchronous Javascript and XML.
The last part, XML, is a bit misleading. It kept that name because that's what is was first use for. But AJAX can now be use to make HTTP request and interface with any language, including PHP.
Depending on the technology you are built on, there are several implementation available. Chances are you have jQuery installed already. In that case, jQuery Ajax, and particularly jQuery.get() would address your concerns.
If you are using a router on the backend, you can simply call a route, specifying it as the url, first argument of the function. Otherwise, you can directly call a file by using the relative path from the html page the javascript is embedded in.
jQuery.get will return anything you echo within you server script. In other words, anything that is directly rendered on the page. You can use a callback catch the data returned and process it.
Example :
$.get('/path/to/file.php', function (data) {
console.log('Here is the data received from the server!', data)
// Process data here
});

Check if a javascript has loaded and then call another javascript

I have a javascript which gets JSON data from URL and loads the data on to the page, then I want to call another javascript to add the slide effects.
There is a simpler solution, i.e using setTimeout. But this solution is not complete because getting data from a URL does not have a fixed amount of time. It varies on every call.
Hence I want to check if my first javascript has loaded and then I want to call the second javascript.
JavaScript is an asynchronous language, or at least, its HTTP API is (mostly) asynchronous.
You shouldn't use settimeout, but you should use asynchronous chaining instead for building a list of causal events. There's a big bunch of libraries out there to assist this, like http://www.infoq.com/articles/surviving-asynchronous-programming-in-javascript
If you're loading content from your own site, then there'll be an onsuccess/oncomplete event when the JSON finally gets loaded, you can assign a callback to it. How it is actually called depends on your javascript framework if you use one.
If you're using data from a remote site in a format called JSONP, you're to define a callback to it, it should be a public function name, like onMyDataArrived. You should add your callback code there. Some frameworks hide this detail from you, they generate a random function which they remove when the data has arrived, and provide an API similar to onSuccess / onComplete instead.
Nowadays, the most popular javascript framework is jQuery, where you can do such things, like:
$.ajax({
url: 'give_me_my_json.php',
dataType: 'json',
success: function(data){
//call your second javascript
},
error: function(){
//WHOOOPSIE... data could not be loaded
}
});

How to hide details in jquery ajax from browser page source

I am using jquery for all my ajax thing, I don't know if that is fine but I use that for now.
I have one text input when user type characters in it I call server side get some values and add them on the view.
Code that I use bellow works fine but I want to improve it a little.
How can I make this ajax call so that users that want to investigate my page source code can't see what I call here?
So basically I want to hide from page source what url, what type and data send I use here, is it possible?
$(function () {
$("#txtSearch").keyup(function (evt) {
$.ajax({
url: "/Prethors/Users/SearchUsers",
type: "POST",
data: "text=" + this.value,
success: function (result) {
$("#searchResult").prepend("<p>" + result + "</p>");
}
});
});
});
No, a user will always be able to figure out what calls you are making if you include it in javascript.
You can compress and minify the javascript, but a determined person will always be able to find your url calls.
Here's a js compression site, for example.
http://jscompress.com/
overall, you shouldn't worry about this. there is no way I'm aware of to hide your ajax calls, but you shouldn't need to.
-you could encrypt the info.
-you could use comet to stream the data on a persistent connection. (super complicated).
-follow good server security practices and not worry about it.
source: here
If you are really worried about this, you could set up kind of an anonymous URL, which will then redirect to where you really want to go based on some variable which is arbitrary.
for example, instead of going to "/Prethors/Users/SearchUsers"
go to "/AnonymousCall?code=5"
from which you could execute the code you want for searchusers
You can't hide client-side code. You can disguise it with minification but sensitive data should always be stored and processed on the server-side.
Use console.clear(); after you ajax calls :P
It just clears the reqs from the console but you still cannot hide client side calls.

Call from JavaScript to server-side code in JSF

I'm looking for an easy way to call a bean's method that will take no parameters and return a string in JSF. The thing that I don't really need is that the method returns an action result and then uses the whole JSF life-cycle to do get me to another view. I need to do that from JavaScript so that I can put together some client-side parts of the application and going over the A4J part of RichFaces has brought me nothing so far.
So here's the scenario again in a step-by-step form:
from JS issue a GET on some address
on the server process that GET and return JSON or HTML (basically a string)
once the request is sent back to the client I want to be able to process it further with JS.
Thanks!
Use a4j:jsFunction and the data attribute.
So roughly you want something like:
<button onclick="callBackend();">Go</button>
<a4j:jsFunction name="callBackend" action="#{myBean.someMethod}" data="#{myBean.someString}" oncomplete="handleResponse(data);"/>
<script>
function handleResponse(response) {
alert(response);
}
</script>
Damo: can you explain why it might only work for the first time the method callBackend is executed? I'm experiencing a strange behavior that the first call succeeds and the next calls are just blocked. I see the server-side code being executed but some strange result is being sent back to the browser (something like the _viewstate and those kind of things).

Categories

Resources