I wish to run some asp.net code on a page generated by Wordpress. Is there a way using XMLHttpRequest() to make JavaScript interact with .aspx page just like a Servlet?
For example, I hope that I can do this in JavaScript:
xmlHttpRequest.open("POST", "http ://some.aspx", true);
send_request("request=add,1,2");
function getReadyStateHandler(xmlHttpRequest) {
//handle_response
}
How to write and configure such an asp page? Does someone know a good tutorial?
Thanks a lot!
You are better of using JQuery for this task.
It is Javascipt library that has exactly functionality that you re looking for
You can call your backend methods to invoke serverside action that would return JSON object. and then in done function process the result.
$.ajax({
url: "test.html",
context: document.body
}).done(function(result) {
var dataFromTheSreverside = result;
$( this ).addClass( "done" );
});
Here you can find a lot of examples
Related
Hello every1 I am both new to this site and html so i wanna ask Can i do something like that
<link href="index.cs">
then use functions If possible how ??
I want to use functions that i declare in my c sharp file fro a button
like i dont know
<button id="button-test" onclick="helloworld()">click</button>
and i ll have a function in c sharp named helloworld like
void helloworld()
{
return;
}
Thnx for ur answers
You can use javascript functions or use asp.net.
You can call the function in controller class using ajax like this
$("#buttonId").click(function (e) {
e.preventDefault();
$.ajax({
url: "/Controller/MethodName/{parameter}"
});
});
you should use ajax and connect to c# controller via ajax
Visit this link:
AJAX Introduction!
Take a look at using Blazor or Blazor WASM:
https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor
You can use C# client side.
I have a global function that returns some string.
I need to access to that function from JavaScript in one of the pages and set returned value to JavaScript variable.
Example:-
var jsvariable = <%GlobalClass.MethodReturningString();%>;
How to do that?
You cannot call C# function like this. you need to create a web service or webmethod
in order to call this function.
Please see this link it will help you.
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Perform the following steps :
Right click on your website or web application and add a WebHandler. The extension for the webhandler is '.ashx'. Let's say you name your handler as 'Handler.ashx'
Open the Handler.ashx file and within the ProcessRequest method write the following :
context.Response.Headers.Clear();
context.Response.Write(GlobalClass.MethodReturningString(););
context.Response.Flush();
In your javascript, perform an ajax call using jQuery :
$.ajax({
url:'someUrl/Handler.ashx',
type:'GET',
success : function(data){
var someJavascriptVariable = data;
}
});
NOTE: This is a quick and dirty write so I'm not guaranteeing that the code will surely work, but it's a point for you to start with.
May i thick You cannot do this but u can access ur c# function using ajax
For Example
$.post('url', {parameter : parameter }, function (result) {
// here the result is your function return value or output
},"json");
URL FORMAT : '/pageurl/methodname'
First of all, as a clarification, it seems that you're not trying to actually call a C# method from Javascript, but rather render the return from a C# method inside the page so that it can be used as a Javascript variable value on the client side.
In order to do that you need to update you syntax like:
var jsvariable = '<%= GlobalClass.MethodReturningString() %>';
Please note that if your class is not in the same namespace as the inherited page from the code behind file, then you need to import its namespace like below:
<%# Import Namespace="GlobalClassNamaspace" %>
The namespace import can also be done globally (and it will be automatically available in all of the site's pages), using the web.config file as described here.
If you were to actually need to call a C# method from Javascript, which would have been needed if you wanted to dynamically use its results from client side code, then that could be accomplished through Ajax.
I have a tricky problem. I am in a situation where I need to use a method defined in a .cs file from a javascript function. The problem is we are using .NET 1.1 and AJAX cannot be used for the application.
Also, I will need to pass a string from the javascript to the server side method. The page where I am implementing the javascript is a .as Any ideas?
I have tried doing a post back and creating a RaisePostBack event handler method (both in the .aspx page and the .ascx user control) but no luck.
It will be greatly appreciated if someone could help me out with the problem.
To be more precise. I have a class Attachment.cs which has a method Delete().
The javascript is called from a span's onclick event. The javascript function's input parameter would be a string which I will need to use to instantiate an Attachment.
I created a method which instantiates an Attachment using a string and calls the corresponding Delete() method for the Attachment object.
Now, I will need to pass the string from javascript function to the method I have created. I cannot use PageMethods.
The Javascript function is like:
// File ID is a string
function DeleteAtt(fileID)
{
//I tried PageMethods here, tried posting the page and getting the value through
// a RaisePostBack event etc. No luck.
}
The cs method I created is like:
public void DeleteAttachment(string ID)
{
Attachment obj = new Attachment(ID);
obj.Delete();
}
Do you mean that Microsoft's "ASP AJAX" is not an option, or do you mean that any jquery/any other library, or your own hand written javascript ajax won't work? ASP AJAX may not be supported by you version of .net, but surely simple javascript will still work, as you want to access the page from javascript.
If this is the case, something as simple as this, using jquery, would work:
function submit() {
$.post(
"pagename.aspx?string=" + variable,
function (data) {
alert("Response: " + data);
});
}
How about adding a callback-url as a query string to the url that you need to submit data to? Example:
Initial Page:(javascript)
function send(){
window.location = "submiturl.aspx?str=var&
callbackurl=http://www.myurl.com/page.aspx";
}
submiturl.aspx then catches both query strings [str] and [callbackurl], performs the action/function and then sends a response back to the [callbackurl]
response.redirect(callbackurl + "?response=" + data);
Initial Page now uses response.querystring to determine if it was succesful/whatever else you want and continues its business.
This definitely does not use ajax, and would be, by no means, asynchronous, but is based on a pretty lengthy history of API/callback & response design.
You can inject an invisible Iframe into the page and the SRC of the iframe can be used to pass data back to the server.
This is a very old technique back before jQuery and Prototype were invented.
See: http://www.ashleyit.com/rs/ for other alternatives.
I'm learning javacript, and I'm about at the point where I want to start doing some asychronous stuff. Here is the gist of my quest:
I have HTML code that looks like this:
<a id='nine' onclick="SendToServer('nine');">Nine</a>
I then want a way to, in Javascript, send back to the server that a#nine was clicked.
function SendToServer(id)
{
//Send that a#nine was clicked back to server
}
I then want some sort of handler function in c# to update an entry in a database.
public void GetMessageFromJSHandler(int id)
{
Item[x][y] = id;
}
I don't want the page to reload, I don't want anything to change on the page, and I want to do this in straight javascript so that I can learn how it works.
This is a GREAT resource: http://msdn.microsoft.com/en-us/library/ms178210.aspx I ended up altering this example for my needs. All Js and very straightforward.
Well, inside the context of your question, you're on the right track. You can use this example: http://www.devx.com/DevX/Tip/17500 to see how to populate your SendToServer function
GetMessageFromJSHandler would probably be called by the ProcessRequest method of an implementer of IHttpHandler, at least in the easiest scenario.
but that way of doing things is really for academic purposes, learning the plumbing as it were. In a production environment, you're much better off using a framework. My personal crack of choices is jquery on the client and ASP.NET MVC on the server, but if you like "regular" ASP.NET (aka webforms) then check out the MS Ajax libraries to see some easier ways of doign things in a scalable & maintainable fashion.
You can mark your page methods with a WebMethod attribute to create stubs for them on the client-side. Here is an example.
Another thing you could do is make your page method static and call it using jQuery's ajax() function. Here is how this way works.
jQuery:
function SendToServer(id)
{
$.ajax({
url: "/GetMessageFromJSHandler",
type: "POST",
data: { 'id': id }
}):
}
function SendToServer(id){
var pageUrl = "SamplePage.aspx?callback=true&ItemId=" +item
if (window.XMLHttpRequest)
{
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("POST", pageUrl, false);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.send(null);
}
On pageLoad you just check the callback flag and call your function
if(Request.QueryString["callback"].ToString() == "true")
{
string id = Request.QueryString["ItemId"].ToString()
GetMessageFromJSHandler(int id);
}
I've written some basic Javascript functions and would like to learn how to enable asynchronous postbacks within a C# 4.0/ASP.net project using this JS code.
For example, I have a script that increments a number when clicked. When clicked again, the number is decremented. I basically load the number from a database, then hide one <span> and show another with the corresponding decremented number on click. This is not complicated javascript; its a simple example. Now when I click the button I want to send this increment/decrement call back to the server to update the database's number.
I realize that I can accomplish something akin to this example using the AJAX Control Toolkit's toggle button. I, however, want to know how to use my OWN javascript to create AJAX functionality.
How do I accomplish this using C# and my custom Javascript code?
I'm not opposed to using the ASP.net AJAX library, I just don't want to use a ready built control. I want to learn the process of creating my own AJAX functionality. I would presume that I will have to use an asp:UpdatePanel, but I don't know how to call C# functions from the client side.
My javascript is not jQuery, in fact I want nothing to do with jQuery until I learn more about javascript and this process.
Simple with no UpdatePanel:
First, add a Generic Handler to your project (.ashx). This will act as our Http endpoint. Our javascript will call it. We could (and probably should), use a web service endpoint but that requires processing the response and complicates the example. A handler returns plain text.
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler
{
// We'll use a static var as our "database".
// Feel free to add real database calls to the increment
// and decrement actions below.
static int TheNumber = 0;
public void ProcessRequest(HttpContext context)
{
string action = context.Request.QueryString["action"];
if (!string.IsNullOrEmpty(action))
{
if (action == "increment")
TheNumber++; //database update and fetch goes here
else if (action == "decrement")
TheNumber--; //database update and fetch goes here
}
context.Response.ContentType = "text/plain";
context.Response.Write(TheNumber);
}
public bool IsReusable { get { return false; } }
}
Next, create your web page and add the async javascript.
<%# Page Language="C#"%>
<html>
<head runat="server">
<script type="text/javascript">
// An XMLHttpRequest object is required to make HTTP requests.
// Try a couple instantiation strategies to handle different
// browser implementations.
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}
function callHandler(action) {
var xmlHttpReq = createXMLHttpRequest();
// We're interested in an asychronous request so we define a
// callback function to be called when the request is complete.
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
document.getElementById("<%= lbl.ClientID%>").innerHTML
= xmlHttpReq.responseText;
}
xmlHttpReq.open("GET", "Handler.ashx?action=" + action, true);
xmlHttpReq.send(null);
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<div>
The Number: <Label runat="server" id="lbl">0</Label>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Increment"
OnClientClick="callHandler('increment');return false;" />
<asp:Button ID="Button2" runat="server" Text="Decrement"
OnClientClick="callHandler('decrement');return false;" />
</div>
</form>
</body>
</html>
The final flow is:
A web page user clicks the Increment or Decrement button which calls our javascript
Our javascript sends a request with the desired action in the querystring to Handler.ashx
Handler.ashx reads the querystring, increments or decrements its static variable, and returns the value
Our callback receives the value and updates our UI.
if your using an UpdatePanel it's very simple with a JavaScript call to __doPostBack. See here for example.
Have a look at this tutorial around AJAX
http://www.w3schools.com/Ajax/Default.Asp
It will give you an overview of using Javascript to GET and POST data using AJAX.
Hope this helps.
Here's a link on how you can incorporate ASP.NET C# with your custom Javascript code.
http://msdn.microsoft.com/en-us/library/bb386450.aspx
It also contains a sample VS 2010 project here:
http://go.microsoft.com/fwlink/?LinkId=185646
Here's generally what's going on here:
In the AjaxIScriptControl solution:
SampleTextBox.cs - takes care of rendering the script control on the page; and attachment to client javascript code (the js file)
SampleTextBox.js - takes care of client side functionality and generates Javascript object of control via prototype
Notes:
This example leverages existing
ASP.NET's built-in control (you
notice SampleTextBox inherits Textbox
and IScriptControl) but you can
render any type of HTML control if
you inherit ScriptControl class
instead.
This solution also chose to separated
the Script control code and website
code in two projects but you can
easily make it into one.
You can easily leverage another Javascript library in your JS file
In my experience so far, this is the one of the more elegant way to incorporate server side code with client side if you are to create re-useable controls for your website. You leverage server side power to do the initial rendering while provide client side capabilities through Javascript.
If you create your C# functions as WCF REST Services or older-style Script Services, then you can easily call your service methods from your JavaScript using a basic XmlHttpRequest (no jQuery or UpdatePanels needed).
Here's a quick jsFiddle I put together: http://jsfiddle.net/ndVeS/
This sample has two text boxes; you enter a value in the first one, click the button, and then that value is passed to a service (an echo service) and returned in the callback. The JavaScript code takes that value and populates the second textbox with it.
You could define a C# WCF RESTful service like this:
[ServiceContract]
public class EchoService : IEchoService {
[WebGet(UriTemplate="EchoMe?val={theValue}, ResponseFormat=WebMessageFormat.Json)]
public string EchoMe(string theValue) {
return theValue;
}
}
If you handle your calls this way, you can separate out your service logic from your presentation (ASPX files), and this allows for easier testing and you can also separate responsibilities from those who build the UI from those that build the business functionality.
I have to admit I'm more of a jQuery person when it comes to this, but I thought it's a great exercise to figure out how the XmlHttpRequest works under the hood. It makes you appreciate what jQuery (or similar framework) provides.
Here's a nice overview of the XmlHttpRequest object and how to use it: http://www.jibbering.com/2002/4/httprequest.html
I hope this helps.
function GetXmlHttpObject(handler) {
var objXMLHttp = null
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject) {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp;
}
function GetDropDown() {
function stateChanged(StatesUpdated) {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
document.getElementById('updateplace').innerHTML = xmlHttp.responseText;
//"updateplace" is you div id which will hold the new data or new page
if (navigator.appName != "Microsoft Internet Explorer") {
}
}
else {
//alert(xmlHttp.status);
}
}
xmlHttp = GetXmlHttpObject()
if (xmlHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
url = "xyz.aspx" //this might be sent to any post data
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
with the above code you can send data to any .cs file also where you can change the data and load it in a new page which will load in the update div and the method should redirect to the new aspx file.
I hope you got the logic :)
if you have any doubts reach me # sankalpa.sam#gmail.com
I know it's not MVC that you're doing, but have a look at the MVC section of the ASP.NET site and you will find a lot of examples of AJAX calls there - MVC doesn't use those dreadful script-soup creating .NET objects. Most will probably be using jQuery - this is an open-source javascript library that can plug into any web app and provides some really nice functionality.
Maybe u r looking for this:
function ajaxscript(){
$.ajax({
type: "POST",
url: |url/methodName|,
data: |variable_name|,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: |some javascript here|,
error: |some javascript here|
});