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/
Related
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 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...
I am using a web method for ajax call, I want to change the text of my asp.net label control after ajax call.
I am changing its text on success of the ajax call,but after post back I am not getting updated value, as its changing on client side.
I want to change text so that it will reflect on post back as well.
How can I change the text of label in WebMethod?
Below is my code
[System.Web.Services.WebMethod()]
public static string RemoveVal()
{
//Do some work
//Return updated Value
//I want to change text here
}
jQuery.ajax({
type: "POST",
url: 'MyPage.aspx/RemoveVal',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var emaillbl = GetClientID("lblEmail").attr("id");
$("#" + emaillbl).html(data);
}
});
<asp:Label ID="lblEmail" runat="server" CssClass="labelclass"></asp:Label>
function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
AJAX call will update control text in client side only. If you want to change label's text after post back , bind the changed value again to the control while page posts back. Like you can call function which binds changed value to label in postback event OR in page load wherever seems fit.
Hi
I used jquery in my application and I have a problem but I think it is necessarly to look at this code :
$("#btnAddToBasket").click(function () {
var id = $("#ProductIDAtBasket").text();
var count = $("#BasketAddedValueText").val();
//ajax request
$.ajax({ type: "Post",
url: "Services/NewE_ShopServices.asmx" + "/" + "GetPrice",
data: "{" + "count" + ":" + count + ", goodcode : " + id + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
async: true,
cache: false,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var res = result.d;
res = res.split(';');
$("#spanFinalPrice").text(res[2]);
$("#spanAbsolutePrice").text(res[3]);
$("#spanDiscount").text(res[4]);
$("#spanCount").text(res[1]);
$("#AddBasketDiv").hide("slow");
}
function AjaxFailed(result) {
alert(result.responseText);
}
As you can see at the following there is ajax send method to web service I get the values and put results using ajaxsucceeded method into the page it works fine and suitable but my problem is that it is basket viewer and I want to be more permanent for example in this page when you go to other page and back to it the contains will be omitted I can use session and cookies in the webservice class but how I can read from jQuery code? what is solution is there any other solution ?
If I am understanding it correctly, you are adding things to a basket, but they are not persisting on other pages? I.E, you add a product to your basket, and then move to another page and the item is not in the basket?
If so you need to check a couple of things:
How are you storing the basket on the server side. Do you put the items in Session?
Are you reading from that basket to pre-populate the basket in a state before you add items in?
I just add another ajax method to my jquery script and put some sever side property and set them by ajax method that was easiest.
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'")