Ajax using JQuery in ASP .NET c# - c#

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()

Related

ASP.NET visual web part + AJAX, can't make it working

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.

WebMethod never be called in asp.net

I am using jQuery to call C# code behind methods. Here is my ascx file code:
ASPX
<div class="dnnFormItem">
<asp:LinkButton id="cmdLogin" resourcekey="cmdLogin" cssclass="dnnPrimaryAction" text="Login" runat="server" />
JQuery
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=cmdLogin.ClientID %>').click(function () {
$.ajax({
type: "post",
url: "Login.ascx/ServerSideMethod",
data: "{sendData: '" + ID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
});
});
</script>
And here is my C# code:
[WebMethod]
public static string ServerSideMethod()
{
return String.Format("Hello");
}
Please help me out to solve this. My WebMethod function in C# is never be called.
your ServerSideMethod() is expecting a parameter sendData. have you tried using an aspx page or an asmx rather than an ascx
You are passing a parameter but the web method doesn't take any parameters, so is likely throwing an exception. Use the error function to find this for sure. This can be done similar to your success callback. Information about that can be found in the Jquery documentation: http://api.jquery.com/jquery.ajax/
for data: "{sendData: '" + ID + "'}",
check if ID really exist??? if if you want to really pass the parameter to ServerSideMethod else remove this line in case you are not passing this parameter to ServerSideMethod.
and change WebMethod,pass parameter sendData
[WebMethod]
public static string ServerSideMethod(string sendData)
{
return String.Format("Hello");
}
url: "Login.ascx/ServerSideMethod"
You'll have to move your "service" to an asmx (or aspx, ashx) file - WebMethods can't be in UserControls..
I've seen some "workarounds" but IMHO, they're not really workarounds per se...or should I say "hacky" and ends up being more convoluted than just going asmx
Hth...

How can I call a method that are in my code-behind via Javascript or Jquery

I have the follow line in my Javascript code
credenciadausuario = '<%= getCredenciada() %>';
In my code-behind I have this method
public string getCredenciada()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
string credenciada = tk.CarregaToken(1, Request.Cookies["token"].Value);
return credenciada;
}
but when I put the debugger in my javascript code, the credenciadausuario variable, receives the string "<%= getCredenciada() %>" and not the return of my method. How can I call my method that are in my code-behind via javascript or jquery ?
It seems all you want to do in your code is get the value of a cookie. Why not do that in JavaScript on the client?
IF possible make use of ajax and do call the method, that will do you task.
check this post : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
This article from Encosia is excellent. It shows how to call a method in your code behind using jQuery ajax.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your code behind you have to give the method the [WebMethod] attribute:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
To call that method using jQuery you would use the following:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Well, to actually CALL your code-behind methods from Javascript, you would have to use ajax. JQuery has a nice $.ajax wrapper for that.
But I think you just want to include some value into the js code once, while it's being generated and sent to the browser. In that case, you need to use a file type which ASP.NET recognizes as a dynamic file.
The easiest would be to put JS code (in a <script> tag) into .ascx files. Then <%= getCredenciada() %> will be executed and will return an actual string which will be rendered into javascript code.
Then, of course, you should include such a control to the page as a regular ASP.NET control.
And I am not saying this is the best way to achieve what you want. Sometimes it's just the fastest.

consuming webservice in Jquery

I used a Jquery truncator solution which is neatly written by Henrik Nyh to have a read more/less functionality. The script here
I wanted to modify this code to be able to keep track of read/unread status by updating database. I worote the code that does the database update in a webservice as follows.
[WebMethod]
public void updateReadStatus(int ID)
{
//code to update the database
}
I added the following to consume the webservice in the Jquery
function updateStatus(){
$.ajax({
type: "POST",
url: "WebServices/myWebService/updateReadStatus",
data: "{'ID': " + $("#lblID").Text + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});
function OnSuccess(reuslt) {
alert(result.d);
}
function OnError(result) {
alert(result.status + ' ' + result.status);
}
}
//and i called this function on this line
full_node.find('a:last').click(function() {
truncated_node.show(); updateStatus(); full_node.hide(); return false;
//The user control that im using this scrip on has a repeater that contains a div that contains the paragraph to be truncated.
<div class="readmore">
<%# Eval("Message_Text")%>
<asp:Label ID="lblID" runat="server" visible="false"
</div>
The truncate script works fine and it gave me the functionality i want, read more/less. But i am not able to get the added functionality i wanted. I am getting "12030 unknown" error, i believe the problem is in the line data:
"{'ID': " + $("#lblID").Text + "}",
how can I bring the value of the parameter ID from the text value of the lable to pass it to the webservice?
text is a function, not a property, so you need to call it with ():
"{'ID': " + $("#lblID").text() + "}",
Also, if you want to call a given WebMethod via Ajax, you'll need to decorate it with the [ScriptMethod] attribute.
You don't say what lblID identifies, but you should either be doing:
$("#lblID").text()
or
$("#lblID").val()
See http://api.jquery.com/text/ and http://api.jquery.com/val/

Problem with jQuery selector and MasterPage

I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")

Categories

Resources