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'.
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 want to call an ASP.NET function from jQuery by AJAX with response.
I have file Controll.aspx where is included javascript code. Next I have /Services/ControllService.asmx, where is the function, which I want call from js.
js code:
$(document).ready(function () {
$('#btn_start').on('click', function () {
$.ajax({
type: "POST",
url: "Services/ControllService.asmx/Start",
data: {},
dataType: "json",
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (err) {
alert("Error:" + err.toString());
}
});
});
});
But I still getting the error 500.
POST http://localhost:56000/Services/ControllService.asmx/Start 500 (Internal Server Error)
k.cors.a.crossDomain.send
n.extend.ajax
Do you have any hints, what do I need to set e.g. in Web.config?
Many thanks.
SOLVED:
1 - I have defined Start function in ControllService.asmx.cs as static.
2 - I have badly configured data. It has to be named by the same way e.g. "sth".
In javascript it should be:
...
url: "Services/ControllService.asmx/Start",
data: JSON.stringify({ sth: "hahaha" }),
dataType: "json",
...
and in ControllService.asmx.cs -> method Start
public string Start(string sth){}
Many, many thanks for your hints.
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 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();
}
I have some javascript that requires a specific URL to call an ASP.NET web service.
When I run the application locally, the url is something like: http://localhost:123456/ProjectName/Default.aspx
But when I upload the application, the domain will change to:
http://myDomain.com/Default.aspx
What's the best way to capture the current URL path and pass it in as a variable to my javascript? Here is my javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:123456/ProjectName/Default.asmx/SkillsList", //CHANGE THE URL!!
//url: "http://myDomain.com/Default.asmx", //The other URL...
data: "{'like':'" + request.term + "'}",
datatype: "json",
async: true,
success: function(data) {
response(data.d);
},
error: function(result) {
alert("error");
}
});
},
minLength: 2
});
});
</script>
I'm using ASP.NET if that helps at all.
Thanks!
post to relative path
url: "/ProjectName/Default.asmx/SkillsList"
Looks like you're writing out to the aspx page. Given that, you should be able to just have ASP.Net tell you via something like
url: "<%= Request.ApplicationPath%>/Default.asmx/SkillsList"