I am using .net1.1 and trying to call a server side method using Jquery on click of browser Close button.My code is not working.I am posting my code below.Will anybody Guide me where did i go wrong?
<body MS_POSITIONING="GridLayout" onbeforeunload="javascript:return test()" >
Ceci est une page cachée. Elle est utilisée pour la gestion du multi-fenétrage.
</body>
function test()
{
debugger;
$(document).ready(function() {
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success");
},
error: function(msg) {
alert("Error! Try again...");
}
});
return false;
})
}
In Code behind
==================
[WebMethod()]
public DateTime GetServerTime()
{
return DateTime.Now;
}
}
The control does not go to this web method,I am not able to debug,COntrol goes to ' $(document).ready(function() ' after that whole block runs.It is not showing any type of error,but alerts are not showing.If I use any other return type instead of DateTime,It is still not working
**When I am Calling this method test on onload,It is showing alert of error Conditon.But I have to call it when broswer is closed.In any Case it is not going to web method.
$(document).ready(function() { ... }) doesn't execute a function but registers a functoin to be executed when the document is loaded.
$(document).ready(function() { ... }) register a function for the load event of the document. You register this function in onbeforeunload event, this function will never be executed. Because when you register the function in onbeforeunload event, the document has already been loaded and is being unloaded.
If you want to call a method in onbeforeunload , just write the JS code to call WebMethod without $(document).ready
function test()
{
// $(document).ready(function() { //delete this
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) { alert("success"); },
error: function(msg) { alert("Error! Try again..."); }
});
return false;
}
Unfortunately, you cannot specifically check for a browser close. Using onbeforeunload will fire when someone is redirected from this page also. Try binding your event using jQuery on DOM load.
$(document).ready(function() {
$(window).unload(function(e) {
e.preventDefault();
test();
});
});
I can't say exactly why your code doesn't because you haven't provided any error information.
Calling web method from script
You need to take a look at your web service, you need to tell it you'll be calling it from script and as the other guy rightly says, you cannot implicitly serialize a DateTime so the laziest way to get this is to just return a string instead.
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string GetServerTime()
{
return DateTime.Now.ToString();
}
Related
I'm changing Jquery version from jquery-1.10.2 to jquery-3.6.3 but the method callings are not working due to this version change. My .NET Framework version is 4.7.2
I have used the new reference like below:
<script src="../Scripts/Version3.6.3/jquery-3.6.3.min.js?version=<%=ApplicationVersion.GetApplicationVersion()%>" type="text/javascript"></script>
calling client side JQuery POST method:
$.post("/employer/employerbrowse.aspx/SelectEmployer",
{ key: key },
function (data, textStatus, jqXHR) {
alert(data);
});
c# method:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false)]
public string SelectEmployer(string key)
{
string strUrl = "";
return strUrl;
}
After calling the "SelectEmployer" method it redirecting to page load only not in the desired page method.
Thanks in advance.
use AJAX to make the call to webMethod
$.ajax(
{
type: "POST",
url: "employerbrowse.asmx/SelectEmployer",
data: JSON.stringify({ key: _key}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
}
);
Further ... I notice your webmethod is in a normal aspx page, whenever ive tried that it hasnt worked and needed to add a Web Service (asmx) but you might be alright... Youd keep js/ajax call in aspx page if using this.
I created a project in Visual Studio named 'MyProject', and Added .aspx file to it named 'MyPage.aspx'.
In 'MyPage.aspx.cs', there is a web method as shown below
[WebMethod(EnableSession=true)]
public static string GetDetails()
{
try
{
var data= HttpContext.Current.Session["mySession"] as myDto;
return myDto.Username;
}
catch
{
return "Sorry";
}
}
Now, I created another project in that same solution named 'NewProject'.
And I have a page in this project as 'NewPage.aspx', from which I am trying to call GetDetails() from 'MyPage.aspx' (MyProject).
So I tried the following code.
NewPage.aspx
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://localhost:2463/MyPage.aspx/GetDetails',
success: function (data) {
alert(data);
},
error: function (response) {
alert('Error');
}
})
});
</script>
but the Web Method isn't getting hit & I get the 'Error' alert displayed.
I also tried this
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2463/MyPage.aspx/GetDetails",
contentType: "application/json; charset=utf-8",
data: '{}',
datatype: "json",
success: function (msg) {
alert('success');
},
error: function (response) {
alert('Error');
}
});
});
</script>
but no luck.
Plz Help...!!
Sounds like a CORS problem.
By default you cant access a service that is not within the origin domain (scheme, hostname, port).
You have to make sure that link http://localhost:2463/MyPage.aspx/GetDetails is available while making jquery ajax call. For that
you can run MyProject in a seperate instance of VS and then run NewProject in another instance of VS.
Check console in inspect element and find a solution for given error.
You can call webMethod of another page. Your code seems correct.
And no need to write whole URL ('http://localhost:2463/MyPage.aspx/GetDetails') of a page, Just write 'MyPage.aspx/GetDetails'.
I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.
I am attempting to use jquery to call a c# function when a button is clicked. What happens is the return variable (msg) is null.
The button code:
<button id="test1" runat="server">Get Text</button>
The JQuery code:
$(document).ready(function() {
$("#test1").click(function() {
$.ajax({
type: "POST",
url: "ServiceDirectoryAdd.aspx/GetCurrentDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
});
The C# function:
[WebMethod]
public static string GetCurrentDate()
{
return "foo";
}
As I said, the return variable, msg, returns null. Is there something I'm doing wrong?
EDIT: After placing a breakpoint in the C# function, it seems that the program is not entering the function.
Did you added script manager to page. If you not added it. Please add it and then script manager "EnablePageMethod" property to true.
Here is the link for that.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
try with indexing the msg
alert(msg[0]); or alert(msg.d);
Have you tried a GET?
$.get("ServiceDirectoryAdd.aspx/GetCurrentDate", function(data){
alert(data || data.d);
});
And edit the webmethod to accept get
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetCurrentDate()
{
return "foo";
}
I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))