I am using Encosia's sample from his website on how to use ajax call
When I click on the div it's working fine and when I replace button instead of div it's refreshing the whole page and I don't find any errors in firebug.
Here is my code:
Script:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#getdate").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").html(msg.d);
}
});
});
});
</script>
HTML:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<div id="Result">Click here for the time.</div>
<button id="getdate" value="Click Me">ClickMe</button>
Code-behind:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
What most probably happens is - the button submits the page so the pages gets reloaded. I had this problem before in some browsers.
You need to specify type="button" attribute.
http://www.w3schools.com/tags/tag_button.asp
Related
I am using Visual Studio 2013.
I tried this sample code and cannot understand one problem I am facing.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "/Default.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtName.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>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
</form>
</body>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + "The Current Time is: "
+ DateTime.Now.ToString();
}
Now we can get 2 types of WebForms when building a 'Web Aplication':-
Select "WebForm" in 'Select Template' section.
Or select "Empty" in 'Template' section and tick 'WebForm' in 'Refernces' section.
I Know the basic difference between these two but why the given code doesn't run in (1) but runs in (2). In (1) it gives 'undefined' as output.
Some one tell me why is it so and how to make it run in (1) type of WebForm.
Change $("#<%=txtName.ClientID%>")[0].value for $("#<%=txtName.ClientID%>").val() and test it.
I want to make a password recovery function where the users needs to enter the mail adress.
The mail adress has to be validated by asp.net. I dont want the site to refresh after reseting password. Thats why I disabled autopostback for my button. The problem is that disabling the autopostback also stopped the validation of the input.
I dont want to use javascript to validate the input.
So is it possible to disable autopostback but keep the validation behaviour?
Thanks alot!
This is my asp.net code:
<asp:Label>Email: </asp:Label><asp:TextBox id="emailTextbox" TextMode="Email" runat="server" CSSClass="emailTextbox"/>
<asp:Button Text="Anfordern" runat="server" CSSClass="ResetPassword" CausesValidation="True"/>
and this is the called ajax behind the button
function ResetPassword() {
alert($("#<%=emailTextbox.ClientID%>")[0].value);
$.ajax({
type: "POST",
url: "/pages/passwordRecovery.aspx/ResetPassword",
data: '{mail: "' + $("#<%=emailTextbox.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//alert(response.d);
}
});
}
I'm trying to change a label text from cs file after I receive a message from the server.
I tried using to put the label in updatepanel but couldn't make it work.
How can i update the display of the label?
Usually this is something along the lines of
myLabel.Text = "Value";
If it's in an UpdatePanel, the rules are a little different. I think you need to get the control, then update its value. Something along the lines of:
Label lbl = (Label) updatePanel1.FindControl("myLabel");
lbl.Text = "Value";
If you are trying to avoid a post back, then you can use ASP.NET AJAX Page Methods to query the server via AJAX and then push the value returned into the label control, like this:
Markup:
<script type="text/javascript">
$(document).ready(function () {
$('.TheButton').click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.TheLabel').text(data.d);
}
});
return false;
});
});
</script>
<asp:Label ID="Label1" runat="server" Text="Nothing" CssClass="TheLabel" />
<br/>
<asp:Button runat="server" ID="Button1" CssClass="TheButton" Text="Update Label"/>
Code-behind:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
Note: ASP.NET AJAX Page Methods are static methods that are not part of the ASP.NET page life-cycle. They do not have access to any of the controls on the page, but are very useful for getting data from the server (in this case the server time). In the interest of simplicity, I used CSS class names on the server controls to make the jQuery selectors simpler.
i am using < div onclick="""> to call the server side .How can i avoid full page refresh when user click the < div>?
Here is my coding.
HTML
<asp:UpdatePanel ID="updatePanel1" runat="server"> <ContentTemplate>
<div id ="cde" runat="server" style="background-color: #00FFFF" > </div>
<asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label>
</ContentTemplate> </asp:UpdatePanel>
Server side
protected void Page_Load(object sender, EventArgs e)
{
//--Register for div onclick function --
cde.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "divMember_Click");
//**Register for div onclick function**
}
protected void divMember_Click()
{
this.Label1.Text = System.DateTime.Now.ToString();
}
public void RaisePostBackEvent(string eventArgument)
{
if (!string.IsNullOrEmpty(eventArgument))
{
if (eventArgument == "divMember_Click")
{
divMember_Click();
}
}
}
I try putting the label within the update panel . But postback will still occur. How can i refresh the label without full page reload?
you can use Jquery .ajax function or pagemethod.YourWebMethod.
Create Web Method in your C# Code and call it using these two functions.
You can do Page Method by EnabledPageMethod="true" in script Manager and use Jquery .ajax function put jquery java script.
This will be on page behind code (create Web Method):
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
As referenced in Default.aspx, this is java script:
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
<head>
<title>Calling a page method with jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="Default.js"></script>
</head>
<body>
<div id="Result">Click here for the time.</div>
</body>
Put the div and Label into UpdatePanel
Try this way,
Keep your label in the Update Panel id"Updatepanel1" with following properties
Update Mode : Conditional
EnableViewState : true(if you are using it)
You need to have an asp:ScriptManager present on your page to use UpdatePanel. See here.
I have a ScriptManager which is added to my MasterPage;
<telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnablePageMethods="true" />
I have a Web User Control which is placed on the master page.
Inside the web user control, I'd like to use PageMethods but it complains that PageMethods is not defined.
function ddlSqlConnections_SelectedIndexChange(selectedValue) {
PageMethods.OnSelectedIndexChanged(selectedValue);
location.reload(true);
}
I added a new ScriptManager to the user control and it complained that only one scriptmanager can exist on one page so
basically how to add a reference to the master page script manager, from the user control?
It doesn't seem to be possible?
Thanks,
Use a regular ScriptManager instead of the RadScriptManager:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
My conclusion was it's not possible with a Web User Control Page Method and I used AJAX with web service instead:
$('.ddlSqlConnections').change(function (control) {
var selectedValue = control.currentTarget.value;
if (selectedValue == 0) {
return;
}
$.ajax({
type: "POST",
url: "AdminService.asmx/AdminConnectionsOnSelectedIndexChanged",
data: "{uniqueName: " + selectedValue + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
location.reload(true);
},
error: function (msg) {
alert('failed to send a web service request; please contact the administrator.')
}
});
});
You could try to Invoke a method in your masterpage from your userconrol.
Page.GetType().InvokeMember("MethodName", BindingFlags.InvokeMethod, null, this.Page, new object[] { });