'To set the value to a (textbox) server control using jquery ajax
In the below mentioned code, I am able to set the value attained from ajax call only if I am using the HTML controls(button and text). If I am using asp server controls like button, I am not getting any output from ajax call even if I use the button as server control and text box as normal HTML control. Thanks in Advance.
AjaxCall.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxCall.aspx.cs" Inherits="SampleLogin.AjaxCall" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Call</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// $('#<%= btnAjax.ClientID%>').click(function () { // If i use this iam not getting any response
$('#submit').click(function () {
alert("clicked");
$.ajax({
type: "POST",
url: "AjaxCall.aspx/HelloWorld",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert(msg.d);
$("#Result").val(msg.d);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="click" id="submit" />
<asp:Button ID="btnAjax" runat="server" Text="GetVal" />
<input type="text" ID="Result" runat="server">
</div>
</form>
</body>
</html>
AjaxCall.aspx.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
namespace SampleLogin
{
public partial class AjaxCall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(EnableSession = false)]
public static string HelloWorld()
{
return "Hello";
}
}
}
Solution 1:[1]
This is because the server side button causes the page to post back to the server...not sure why would you want to use the server control for making a ajax call?
Solution 2:[2]
I used preventDefault function its working for me now
<script>
$(document).ready(function () {
$('#<%= btnAjax.ClientID %>').click(function (e) {
alert("clicked e");
e.preventDefault();
$.ajax({
type: "POST",
url: "AjaxCall.aspx/HelloWorld",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
$("#<%=txtAjaxVal.ClientID %>").val(msg.d);
}
});
});
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bazz |
Solution 2 | Vignesh |