Ajax method call
Your method returns JsonResult
. This is MVC specific and you cannot use it in a webforms application.
If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
And then to call the method:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
And here's a full working example I wrote for you:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/sayhello',
data: JSON.stringify({ name: 'John' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// Notice that msg.d is used to retrieve the result object
alert(msg.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.
jQuery AJAX function call
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
ajax calling C# method
ServerSideMethod
should be declared static
:
[WebMethod]
public static string ServerSideMethod()
and you can't change Label1.Text
from inside ServerSideMethod
since it's static
.
How to call php function inside ajax method
Generally you will have files that contain functions/definitions and others that handle requests. (This is not necessary, just common practice)
Files that handle requests will include any relevant functions/definitions from those other files
For this case, let's use functions.php
to contain your main functions and actions.php
as a page to handle requests
See the below setup
// functions.php file
function get_team_members(string $team_name){
// return a list of members based on $team_name
}
// actions.php file
include "functions.php";
$action = $_POST["action"] ?? "";
$data = null;
switch($action){
case "get_team_members":
$data = get_team_members($_POST["team"] ?? "");
break;
}
echo json_encode($data);
// js file
$(document).ready(function() {
$("#your_teams234").change(function() {
var team = $("#your_teams234").val();
$.ajax({
url: 'actions.php', // update the url to request from actions.php
method: 'post',
data: { // update data to reflect expected data
action: "get_team_members",
team: team,
},
})
.done(function(requests) { ... })
})
})
Why my simple ajax call to a controller method is not working?
Try this syntax
$.ajax({
url: '/Client/Login/ValidateLogin',
type: 'POST',
data: dat,
success: function (result) {
/// $('#result').html(result);
alert("Success!");
},
error: function (xhr, status, error) {
var err = xhr.responseText;
alert(err);
}
});
and when you use Ajax you have to use div and partialview instead of view to return
How can I make many jQuery ajax calls look pretty?
Make common function like this:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
var doAjax_params_default = {
'url': null,
'requestType': "GET",
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
'dataType': 'json',
'data': {},
'beforeSendCallbackFunction': null,
'successCallbackFunction': null,
'completeCallbackFunction': null,
'errorCallBackFunction': null,
};
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//make sure that url ends with '/'
/*if(!url.endsWith("/")){
url = url + "/";
}*/
$.ajax({
url: url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
beforeSend: function(jqXHR, settings) {
if (typeof beforeSendCallbackFunction === "function") {
beforeSendCallbackFunction();
}
},
success: function(data, textStatus, jqXHR) {
if (typeof successCallbackFunction === "function") {
successCallbackFunction(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
},
complete: function(jqXHR, textStatus) {
if (typeof completeCallbackFunction === "function") {
completeCallbackFunction();
}
}
});
}
then in your code:
$('.button').on('click', function() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `your url`;
params['data'] = `your data`;
params['successCallbackFunction'] = `your success callback function`
doAjax(params);
});
How to put ajax request inside function and call it when necessary?
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()
method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Related Topics
Easiest Way to Read from a Url into a String in .Net
Why Does Enumerable.All Return True for an Empty Sequence
Loading Multiple Versions of the Same Assembly
Static Generic Class as Dictionary
C# "Internal" Access Modifier When Doing Unit Testing
Filter/Search Using Multiple Fields - ASP.NET MVC
Transactionscope VS Transaction in Linq to SQL
What Is an MVChtmlstring and When Should I Use It
Web API How to Add a Header Parameter for All API in Swagger
Find Index of a Value in an Array
How to Compare Values of Generic Types
How to Protect Resources That May Be Used in a Multi-Threaded or Async Environment