This question is with reference to my another question Auto complete not working.
That problem is still there in my code but I thought of doing this other way. I am thinking of calling my webservice from another javascript function and pass the value returned from the service to this autocomplete function as when I try to pass some dummy values to this jquery function its running fine. i am not sure y its is not calling my webservice.
Though now i have written another function to call my service and get the request -
function SendRequest()
{
debugger;
SearchIssues.GetServerResponse(document.getElementById('ctl00_ContentPlaceHolder1_txtIssueNo').value, OnComplete, OnError, OnTimeOut);
}
function OnComplete(arg)
{
alert(arg);
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
In the script manager tage I have added the reference of my webservice -
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/SearchIssues.asmx" />
</Services>
</asp:ScriptManager>
I have updated my autocomplete function as -
$(function() {
debugger;
$(".tb").autocomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] });});
Here I have passed dummy data in source which is working fine.
the signature of my webservice is as -
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetCompletionList(string prefixText)
{....
}
But its still not calling my webservice and is returning some javascript error as -
SearchIssues is undefined
Please Help
Thanks
this worked for me
[WebMethod]
public static Array GetCompletionList(string code)
{
.....your code
}
$.ajax({
type: "POST",
url: "CompletionList.aspx/GetCompletionList",
data: '{"code1":"' +code1 + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (c2) {
....your code
});
});
1> I think while calling you should have full namespace
NameSpace.SearchIssues.GetServerResponse(document.getElementById('ctl00_ContentPlaceHolder1_txtIssueNo').value, OnComplete, OnError, OnTimeOut)
2> Your service class must have [ScriptService] attribute.
3> Test your relative URL for the service
"~/SearchIssues.asmx"
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 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'm trying to execute a server side method using this technique:
Javascript Ajax function
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "Jquery Site.Master/storeLocal",
datatype: "json",
success: OnSuccess(brand),
});
}
function OnSuccess(brand) {
alert(brand);
}
C# method:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
}
line of code to execute is:
<li>
<a class="strong" onclick="storeLocal('petzl','harness')" href="About.aspx">Harnesses</a>
</li>
but its not executing correctly is there any particular error in my code?
reasone i am using this method is because i want to have a dynamic menu for a small project and wish to store in session what specific "li" did a user select in session so that i can load the content in the redirected page.
Thanks alot
Adrian
There is no return in your method that is might be the poblem, you method should be like as below
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return "value" +brand;
}
There are a couple of errors I can see with your ajax request:
The url parameter value isn't a proper URL.
Your not assigning your OnSuccess method correctly.
Try changing it to:
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "ProperSiteUrl/storeLocal",
datatype: "json",
success: OnSuccess,
});
}
And you aren't returning anything from your storeLocal web method. Try changing it to:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return ...;
}
Also, your sending JSON to the server, however, for a single parameter it you might find it easier just to send it as key/value pair e.g.
...
data: "brand=" + brand
...
i am not sure if your code is right! you have given both href and onclick and the page might navigate to about.aspx even before the onclick ajax event is completed.
try to remove the href or put the onclick event inside a href='javascript:storelocal()' and return the value from webmethod.
keep a breakpoint in the webmethod and see if the content is getting passed to the webmethod or not.
The url and success doens't look good.
1 - Within the ajax call you don't pass a argument to the success function. it will be returned something by the webmethod specified in c#.
you specify data in the data propriety, and that is used as the arguments passed to the webmethod.
2 - You can't call the webmethod using you master page, it has to be specified in the page that you are working. the aspx file not the master.
The page inherits from master, but it's not the master. Is a page with specification of the master page file.
Try this to identify errors, this for seeing what is returned
error: function (error) {
alert(JSON.stringify(error));
}
how can i use ajax to call a server side method i tried this code but it gives me the alert error messsage and i can't find my problem please help and thank you :
enter code here
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ImageEditor_UserControl.ascx.cs" Inherits="ImageEditor_UserControl" %>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=uploadButton.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "ImageEditor_UserControl.ascx/helo",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function () { alert("success"); },
error: function () { alert("error"); }
})
return false;
});
});
</script>
<asp:Button ID="uploadButton" runat="server" Text="Upload" />
C# Code
[WebMethod]
public static string helo() {
return "Message from server.";
}
You should call *.asmx files (there are other options but this is for the beginning).
Look out for tutorials on web services & ajax consuming.
Have you checked on the line $('#<%=uploadButton.ClientID %>').click(function () { that the
<%=uploadButton.ClientID %> is actually replace by the value and not taken literally?
Do you use firefox? if yes, install the addon "FireBug". Enable firebug to check the request and the response.
Firebug will show you sometimes the error message returned from the server, as in you jquery syntax you are not loading the attributes for the method anonymous method callback for error.
error: function (req,error) { alert("error: " + req.statusText); }
This will give you a heads up on what is going wrong.
Unfortunately you cannot call a page method (server side method) that is a part of a user control. You will have to use a method in an aspx page.