I was trying to implement this simple example http://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx
But it doesn't work, it gives
Failed to load http://site/path/path/pagename.aspx/GetCurrentTime resource: the server responded with a status of 500 (Internal Server Error)
Client side
<script src="http://.../jquery-1.7.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "pagename.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
Server (.cs file)
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
There is no such function failure in the ajax definition. You need to rename it to error. Check the source : jQuery.ajax()
P.S also I advice you to use console.log, not alerts. console.log your name parameter to see if return proper value. Check JSON.stringify for creating your data.
Related
I have a form that I am submitting using an ajax call to an asmx web service. The data successfully inserts into the database, however; neither the success or error function is being triggered. The first alert works. Any ideas?
My jQuery:
$("#AddSupplierBtn").click(function()
{
alert("This is the first alert");
if ($("#AddSupplier").valid())
{
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/TestMethod",
data: JSON.stringify({
SupplierName: $('#SupplierName').val(),
SupplierType: $('#SupplierType').val(),
SupplierPremium: $('#SupplierPremium').val(),
SupplierLocation: $('#SupplierLocation').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("Working - " + msg.d);
},
error: function (xhr,status,error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
});
}
});
I changed the below button type from submit to button and it worked:
<button type="button" class="btn btn-primary" id="AddSupplierBtn" name="AddSupplierBtn">Submit</button>
my .aspx page has a javascript ajax call to the .cs webservice written in the same project under App_Code folder. There are many ajax webservice calls that get called but when I added a new webservicve method and tried to call from javascript, it doesn't get fired. I put a break point in the new webservice call but the visual studio (community edition 2013) does not stop or not get there. Any common/generic reason(s) for this behavior?
Please share your code or use below code..
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(function () {
$("[id*=submitbtn]").click(function () {
var username = $.trim($("[id*=txtUserName]").val());
var userage = $.trim($("[id*=txtUserAge]").val());
$.ajax({
type: "POST",
url: "Service.asmx/GetUserDetails",
data: "{ username: '" + username + "', userage: " + userage + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
return false;
});
});
I am trying to use JQuery ajax in asp .net c#. The code I am using is ...
HTML FORM:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
JQuery Part :
<script type="text/javascript">
function ShowCurrentTime() {
//alert(window.location.pathname);
$.ajax({
type: "POST",
url: "Display.aspx/GetCurrentTime",
data: '{name: "' + $("#< %=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
CS PArt:
using System.Web.Services;
This part below is under partial class which inherits from Page class.
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello "+ name +"! " + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Problem:
It is not working. Please let me know if I am missing any setting or any name space. Or any thing. URL I Put in ajax Call is correct as I verified it by
var pathname = window.location.pathname; I supplied data also while calling ajax.
Maybe changing
failure: function (response) {
alert(response.d);
}
to
error: function (response) {
alert(response.d);
}
Will help find the issue.
I don't see a failure callback in the docs - http://api.jquery.com/jquery.ajax/
The things I can see right off the bat:
$.ajax doesn't take a "failure" parameter, but rather "error." Even
then, you should be using .done() and .fail() instead (see
http://api.jquery.com/jQuery.ajax/)
Your error handling function will be triggered when your page method
throws an exception. The first parameter is a jqXHR object, not a
JSON response from .NET (see the same link as from #1).
Your page method should not go UNDER the page class, but within it.
JQuery has some error
$("#< %=txtUserName.ClientID%>")[0].value
need to be
$("#<%=txtUserName.ClientID%>")[0].value
or
$("#<%=txtUserName.ClientID%>").val()
I have function on .cs page
[System.Web.Services.WebMethod]
public static string getdata()
{
ProductBAL objbal = new ProductBAL(); // Calling class
int i = 0;
i = objbal.get_last_orderid(); //Select query
i = i + 1;
ProductDAL objdal = new ProductDAL(); // Calling class
objdal.insert_new_orderid(i); //Insert query
HttpCookie orderid = new HttpCookie("orderid");
orderid.Value = "MP_" + Convert.ToString(i);
Response.Cookies.Add(orderid);
Response.Cookies["orderid"].Expires = DateTime.Now.AddHours(5);
string abc=Convert.ToString(i);
return abc;
}
My Html page code is
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>calling function from .cs</title>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
$.ajax({ type: "GET", url: "default.aspx/getdata()", success: function (data) { });
alert("Done");
}
</script>
</head>
<body>
<form name="ecom" method="post" action="https://www.google.co.in/">
<input id="Submit1" type="submit" name="submit" runat="server" value="Submit" onclick="return Submit1_onclick()">
</form>
</body>
I am trying to call my web side function to client side on submit click.
Am I missing something? Please give a demo from my above code
function Submit1_onclick() {
// alert("Hello");
$.ajax({
type: "GET",
url: 'demo.aspx/getdata',
data: "{}",
//"{character:'M'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
//alert("success");
alert("This is ajax call:");
},
error: function() {
//alert(Error);
alert("something went wrong");
}
});
// alert("Done");
}
[WebMethod()] //U have to declare this method as a web method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string getdata()
{
On your url try : "PageName.aspx/MethodName". Also check out this blog post by Dave Ward :
Using jQuery to directly call ASP.NET AJAX page methods
Below line is error prone. do not include "()" in url method name.
$.ajax({ type: "GET", url: "/getdata()", success: function (data) { });
Replace above line with
$.ajax({ type: "GET", url: "/getdata", success: function (data) { });
See the following working example
// Code behind method declared static
[WebMethod]
public static string GetSquare(String value)
{
return "hello" + value;
}
your button whose click this has to be done
<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" />
script for this
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSquare",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "test" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
From your comments I have gathered that you are verifying if this method is working by checking for new entries in a database table. The data in the database could be missing for other reasons rather than the query. To verify, try a more simple web method, and go from there.
eg,
Html :
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitClick();" />
Javascript :
function submitClick() {
$.ajax({
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "default.aspx/getdata",
success: function (data) {
console.log(data);
alert("success" + data);
},
error: function () {
alert("something went wrong");
}
});
return false; // Note: the return false will prevent postback
}
C#
[System.Web.Services.WebMethod]
public static string getdata()
{
return "Hello World!";
}
If you do not see a success response, then the problem is indeed with your javascript, or rather with the site setup which is somehow preventing callbacks from javascript.
If the method succeeds then it is likely that your database insertion script is raising an error and you should step through it to see that cause.
I have a jquery ajax call asp.net web service question. I want to validate a textbox in asp.net web page.
The validator is:
<asp:CustomValidator ID="CustomValidatorUser" runat="server" ControlToValidate="TextUserName"
ErrorMessage="Minimum of 6 (six) alphanumeric characters."
ClientValidationFunction="ValidateUserName" Display="Dynamic"
ValidateEmptyText="True" ></asp:CustomValidator>
The jquery code is(updated 2nd):
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script src="../jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': " + $("#TextUserName").val() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
</script>
<div>
General user information</div>
<p>
</p>
<table cellpadding="2">
The web service code is:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UserNameWebService : System.Web.Services.WebService
{
[WebMethod]
public bool ValidateUserName(string strUsername)
{
string UserNameCreated = strUsername;
string AD_Server = System.Configuration.ConfigurationManager.AppSettings["AD_Server"];
DirectoryEntry entry = new DirectoryEntry(AD_Server);
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(objectClass=user)(samaccountname=" + UserNameCreated + "))";
SearchResultCollection results = deSearch.FindAll();
Match match = Regex.Match(UserNameCreated, #"^[a-zA-Z0-9]{6,}$", RegexOptions.IgnoreCase);
if (results.Count > 0)
return false;
else if (match.Success)
return true;
else
return false;
} }
But I got an error:
ValidateUserName is undefined.
Please help me to correct the error.
Thank you very much!
There are actually several problems with your code.
1) $("#TextUserName") will not work in this context because asp.net will render the server-side TextBox control with a different ID. You would need to do this instead:
data: "{'strUsername': " + $("#<%=TextUserName.ClientID%>").val() + "}",
2) The json in your data attribute is not formatted correctly, you need single quotes ' around the value like this:
| |
V V
data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
3) You need to put your Jquery ajax call inside a function, which in your case is called ValidateUserName. It takes two parameters source and args. The responsibility of this function is to set the value of args.IsValid to either true or false. So you will need to provide a function to be called when the ajax call succeeds that can perform this logic. Like this:
function ValidateUserName(source, args) {
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
args.IsValid = result.d;
}
});
}
4) As you can see in the code above, you don't actually need to use jquery to get the value from the textbox because you can access it like this args.Value.
5) You need to add async: false otherwise by the time IsValid is set, the code that sets the visibility of the message will already have been executed, and so nothing will happen.
You need to encase your ajax function in a function call ValidateUserName so it matches ClientValidationFunction.
function ValidateUserName(){
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': " + $("#TextUserName").val() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Even then, this isn't returning a value. I think you'll need to use the success option of the $.ajax function to set a boolean value to return to the function.
So you would do something like:
function ValidateUserName(){
var isValid;
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" + $("#TextUserName").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
, async: false
, success: function(data){
isValid = data;
}
});
return isValid;
}
Notice I've also set async to false.