-1

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.

5
  • What is the main problem? What is your main goal? What is the expected result, and what result are you getting instead? And finally, what have you already tried in order to achieve your goal? Explain all of these things in detail, then use your code to accompany your explanation. Help us help you. Commented Jan 26, 2023 at 2:24
  • 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. Commented Jan 26, 2023 at 2:32
  • the WebMethod method is supposed to be static. public static void SyncData(string data) Commented Jan 26, 2023 at 4:55
  • I changed the static, but Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Response.get' appears Commented Jan 26, 2023 at 6:56
  • see my edit to my answer below - I post some working code based on your example. Commented Jan 26, 2023 at 22:52

2 Answers 2

1

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:

enter image description here

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>

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much, the two examples worked too! I would like to ask two questions 1. What does JSON.stringify mean? Why do I change data: JSON.stringify({data : sYesNo }) to data: { 'data': sYesNo }, and then it won't work? 2. Why does it fail if I put the function in $(document).ready(function () {}? When does ajax need to use ready(function () and when does it not?
data: "{data : '" + sYesNo + "'}",
You could have used the above format, note how we need a CORRECT string, and you need {data: 'Yes' } as the string. So, you don' have to use JSON.stringify, but it avoids the need for "messy" string concatenation. If you send { data : 'sYesNo'}, then you sending the string sYesNo, not the "variable" value. So you need a string, and it has to be json format. So either you "build up" the string as correct json format, with the js variable concentrated.
on document ready? Gee, why even bother. What that does is run code to "attach" and "create" a click event for a given control. its rather confusing, and running code to create + attach a click event? Pure confusing! Where I come from, you drop a button, or a control and then add a click event to call a routine. So, you drop a button on a form? then add a onclick event. At then you be able to read that stuff and de-bug it a few months later. So your other format can be used, but I avoid that approach like the plague. That approach can be handy to attach events to "many" controls at once.
GET is typical used when you pass the values in the URL (so, we would not be using data: part of the ajax call. I suppose you could correctly form the URL with www.whatever.com/MyPage.aspx?data="some value". However, using POST + data, and stringify tends to be better. So, you can use GET, but then data: {} will be blank. I always use post - be it sending no data, or for something that returns one value, or maybe many values. You can (should be able to use the URL, and that really amounts to what is called a REST call - you put/pass the values in the URL). Both can and should work.
|
0

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:

  1. Using control's ClientID for event binding

    $('#<%=RadioButtonYes.ClientID%>').click(function () {...}

    $('#<%=RadioButtonYes.ClientID%>').click(function () {...}

  2. 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.

9 Comments

I changed it, but still no any response. Do I need to change it to public static void SyncData(string data)? But if I change it, an CS0120 error will occur again.
Did the radio clicked function be triggered? You could add console.log or alert to check it.
Already added, but I don't know why there is no response at all. anotepad.com/notes/rh9q4j3f
If you've added ClientIDMode="Static" attribute to the radio controls, in $(document).ready function, we do not need to use ClientID, we could use $('#RadioButtonYes').click(function () {...});, $('#RadioButtonNo').click(function () {...}); for click event binding. For debugging, at first we should make sure the handler function will be fired when radio item is clicked, like this sample jsfiddle.net/p2yzLqu1/1
I tried it, jquery alert is no problem. But ajax still has not responded, can not find any reason. anotepad.com/notes/rh9q4j3f
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.