I changed the code with a simple like these
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#RadioButtonYes').click(function () {
var enterdata = document.getElementById("RadioButtonYes").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text1 = "ajaxyes";
alert(text1);
},
failure: function (response) {
alert(response.d);
}
});
});
$('#RadioButtonNo').click(function () {
var enterdata = document.getElementById("RadioButtonNo").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text2 = "ajaxno";
alert(text2);
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<div>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" GroupName="G" />
</div>
.cs side
I tried to add some debugging messages, but it didn't work.
public partial class Radio_Button__radiobutton03ask : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void SyncData(string data)
{
if (data != "")
{
if (data == "RadioButtonYes")
{
Response.Write("SyncDataYes");
//return RadioButtonYes;
}
else if (data == "RadioButtonNo")
{
Response.Write("SyncDataNo");
//return RadioButtonNo;
}
else
{
Response.Write("SyncDataOther");
}
}
}
}
I am helping the company to debug some old projects(C# webforms), but struggling to simple ajax.
The goal is when pressing the radio button run ajax "ajaxyes" and .cs "SyncDataYes" message normally, but the above code does not respond when pressed.
I have tried alot of fixes i found online but none seem to work well for, if someone could help, it would be greatly appreciated.
CodePudding user response:
first, there is a LOT of issues here.
first up:
[WebMethod]
public void SyncData(string data)
Why are you marking/making the routine as "void". Void of course in c# means that the function will NOT return anything!!!! - That should be a first obvious issue!
And since you using this inside of the web page (as opposed to a separate asmx page? Then you need to set the routine as static - since NO page class instance will have been created here (there is NOT post back).
next up:
Response.Write("SyncDataNo");
WHY would you try and use Response.Write? Response write is ONLY for writing into a web page. But the WHOLE IDEA of ajax is the web page is not and will not be sent up to the server for code behind to operate on. So, response write does not make sense AT ALL here! It can't be used, and you can EVEN see that the compiler does not allow this (now that you fixed and removed the void from that routine).
A so called "ajax" call?
The idea here is that you do NOT have to post back the web page. This is great since you don't get the browser "spinner" and all that waiting time. It also great since it runs VERY fast since you don't and are NOT posting the web page back to the server.
Of course the big downside is then the code behind can't see nor use, nor modify any of the controls on the web page. (since the web page is still sitting on the users desktop). So code behind for a web method can't see nor modify controls on the page (the calling JavaScript and ajax call HAS do to that change of controls).
So, lets use all of the above information, and fix this code.
Lets make a simple C to F temperature converter.
So, first up, that web method is to return a value, so we remove the void.
next up, as I stated, the page class "instance" is NOT re-created when we call such a web method, so that method ALSO MUST be marked as static. (I assume you know what that means, right???).
Ok. So the web method should look like this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Double ConvertToC(Double MyC)
{
Double CelResult = (MyC * 1.8) 32;
return CelResult;
}
So, we HAVE to make this routine static. (the page class is not re-reated, and the web page is STILL sitting on the users desktop).
So, say our markup looks like this:
<div style="text-align:right;width:20%">
<label style="font-size:large">Enter Celsious Tempature</label>
<asp:TextBox ID="txtC" runat="server" style="font-size:large;margin-left:5px;text-align:center"
TextMode="Number" Width="80px" Wrap="False"
ClientIDMode="Static">
</asp:TextBox>
<br /> <br />
<div style="text-align:center">
<asp:Button ID="cmdConvert" runat="server" Text="Convert to °F" CssClass="btn"
OnClientClick="MyConvert();return false"/>
</div>
<br />
<label style="font-size:large">Fahrenheit</label>
<asp:TextBox ID="txtF" runat="server" style="font-size:large;margin-left:5px;text-align:center"
Width="80px" Wrap="false"
ClientIDMode="Static">
</asp:TextBox>
</div>
<script>
function MyConvert() {
var txtC = $("#txtC");
var txtF = $("#txtF");
$.ajax({
type: "POST",
url: "Autocom.aspx/ConvertToC",
data: JSON.stringify({ MyC: txtC.val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyReturn) {
txtF.val(MyReturn.d);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status ': ' xhr.statusText
alert('Error - ' errorMessage)
}
});
}
I'm also a bit lazy, so I used clientID mode = static, as that makes the jQuery selector nice and easy to type in.
So, when we run the above, we get this result:
so, now your "mess".
it not particular what you goal here is with your sample.
(going for coffee, but study, and try the above).
Edit: Try this sample code
Your c# method in the page:
[WebMethod]
public static string SyncData(string data)
{
string sResult = "";
if (data != "")
{
if (data == "Yes")
{
sResult = "SyncDataYes";
}
else if (data == "No")
{
sResult = "SyncDataNo";
}
else
{
sResult = "SyncDataOther";
}
}
return sResult;
}
And your markup is this:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server"
Checked="true" GroupName="G"
onclick="MyBtnClick('Yes')"
ClientIDMode="Static"
/>
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server"
GroupName="G"
onclick="MyBtnClick('No')"
ClientIDMode="Static"
/>
<br />
<h3>Result</h3>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function MyBtnClick(sYesNo) {
$.ajax({
type: "POST",
url: "TestAjax.aspx/SyncData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({data : sYesNo }),
success: function (MyResult) {
$('#TextBox1').val(MyResult.d);
},
failure: function (MyResult) {
alert('error');
}
});
}
</script>
CodePudding user response:
Since ASP run at server control's ID will be generated different ID in client side, so these 2 event handlers binding will not work.
$('#RadioButtonYes').click(function () {...}
$('#RadioButtonNo').click(function () {...}
You could try 2 solutions:
Using control's ClientID for event binding
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
Adding ClientIDMode="Static" attribute to ASP control
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" ClientIDMode="Static" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" ClientIDMode="Static" GroupName="G" />
** UPDATE:**
Your code also has two more problems:
1 - DataType of your ajax request (json
) does not match with response type from server code (text/plain
). You could check demo of not matching dataType of ajax request here: https://jsfiddle.net/p2yzLqu1/3/
2 - You were using wrong ajax's callback function failure
. We should use done
(success) and fail
(error) callback functions instead. Please check sample of using done
and fail
callback at above demo.