Ajax call to c# function not working - c#

I'm trying to use Ajax to call a C# function but the call is not working.The script shows the hello message but does not show the success/error message.What am i doing wrong
Java script
<script type="text/javascript">
$(document).ready(function () {
$('#btnsave1').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function () {
alert('Successfully Saved');
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
C# Method
protected void apply()
{
MessageBox.Show("hi");
}

Try this:
[WebMethod]//write [WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
data:'{}',
success: function (result) {
alert(result);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});

Few things you need to fix here. First: there's no MessageBox in webforms. change the apply() method to return string:
protected string apply()
{
return "hi!";
}
Second: Use '#btnsave1' to '#<%= btnsave1.ClientID %>' to get server generated id for button and also catch the string returned by apply() method. Your script should look like:
<script type="text/javascript">
$(document).ready(function () {
$('#<%= btnsave1.ClientID %>').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function (data) {
alert(data);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
</script>
Third: Make sure you have referenced jquery in the head of your page:
<head runat="server">
<script src="Scripts/jquery-1.8.2.js"></script>

Related

Posting to WebMethod with ajax error

Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>

Accessing PageMethod from aspx page

I have a webforms application and need to make an jquery ajax call to a PageMethod (i.e. WebMethod) in code behind from my aspx page. So far it does not work for me. Is this possible?
Here is my code:
$(function()
{
setInterval(function(){
$.ajax({
type: "GET",
url: "/ClientBillingBillDetails.aspx/MyPageMethod",
data: {someData: '<%= TheData %>'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
}
});
}, 10000);
});
[System.Web.Services.WebMethod]
public static string MyPageMethod(int someData)
{
return "";
}
Is something wrong with my URL or something else?
Thanks
Try This:
$(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "/ClientBillingBillDetails.aspx/MyPageMethod",
data: "{ 'someData': '<%= TheData %>' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
}
});
}, 10000);
});
Use type as post and make sure if you have ajax.jquery library reference added in solution.
Also i think you can remove '/' in specifying method..
Just use "ClientBillingBillDetails.aspx/MyPageMethod".
Else you can use simple pageMethods using scriptmanager

How to add jQuery DataTable in this Javascript

Is it possible to add the following jQuery DataTable?
$('#myDataTable').dataTable({
});
to this query?
$(document).on('click', '#PlayStatisticeight', function (e) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({
});
$(function () {
$("#PartialViewTopPlayedTracksList").load('#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
});
I don't know how and if it is possible to do so? any help is highly appreciated :)
Yes, just call it once the new partial has been added to the DOM, in the success callback function.
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
});
},
you can initialize datatable, after the partialview is appended on the view in the ajax call complete function like this:
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({ });
});
}

Ajax Call in asp.net

I am making JQuery Ajax call in asp.net, I am returning String with my WebMethod, But on success of ajax call I am getting complete HTML of page in result.I also used type: "get" but no luck, below is my code for ajax call
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData", //url to point your webmethod
success: function (Result) {
if (Result != "")
alert( Result);
},
error: function () { alert('error'); }
});
[System.Web.Services.WebMethod()]
public string GetData()
{
//getting value from Database and returning
}
I am calling this Ajax in MyPage.aspx
Try it like this. With the contentType: "application/json; charset=utf-8"
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData", //url to point your webmethod
contentType: "application/json; charset=utf-8",
success: function (Result) {
if (Result != "")
alert( Result);
},
error: function () { alert('error'); }
});

Jquery Ajax call in asp.net Progress Bar update

I am doing jquery ajax call in asp.net, I am getting some value from database in a textbox and on base of it I am making jquery progressbar.
Its getting value in textbox, but its not taking value of progress bar first time, I have to reload the page for value of progress bar.
Below is my code
$(function () {
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
[System.Web.Services.WebMethod()]
public static string GetCount()
{
//Get values from DB and return it
}
I also tried with document.ready but no luck, Which event of Jquery should I use to make my progress bar on first time.
try this:
async:false, add to ajax call
$(document).ready(function(){
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
})
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:false,
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
ajax means Asynchronous, that said, means that you need wait untill your first request suceed, and after pocess with value.
Some pseudocode:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
//HERE ASSIGN TO PROGRESS BAR
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
// --------------------------
},
error: function () { alert('error'); }
});

Categories