Ana
Ana

Reputation: 113

get return value from codebehind from ajax function

I want to get value of currency from codebehind that then I call it using ajax, but I got nothing, it just show error, here the code

function js

  function showCRate2(obj) {
            var selectedCurrency = $('#<%=ddlPaymentCurrency.ClientID%>').val();
            console.log(selectedCurrency);
            if (selectedCurrency != null && selectedCurrency != "") {
                $.ajax({
                    type: "POST",
                    url: "TopUp.aspx/GetCRate",
                    data: '{id:"' + selectedCurrency + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var o = response.d;
                        $('#<%=hfCurrencyRate.ClientID%>').val(o.RateBuy);
                        $('#<%=hfCR.ClientID%>').val(o.RateBuy);
                    },
                    error: function (response) {
                        alert('error')
                    }
                });
            }
        }

and this the function in codebehind, return object(that later I need the value of it's RateBuy attribut (decimal)

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static OLServiceReference.CurrRate getCurr(int id)
{
    var CR = client.GetCurrRates(id);
            return CR;
    }

and these another related control

<asp:DropDownList ID="ddlPaymentCurrency" CssClass="form-control" runat="server"   onChange="showCRate2()"></asp:DropDownList>
<input type="text" id="hfCurrencyRate" runat="server" class="form-control" placeholder="" style="width: 230px" readonly="readonly" />
<asp:HiddenField ID="hfCR" runat="server" /></div>

on calling showCRate2(obj) just error alert occured (error: function(response)) .I expect that form hfCurrencyRate show the Currency of Buy Rates. How to fix this? Any Idea?

Upvotes: 2

Views: 1894

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34846

The method name in your AJAX call does not match the name of the method in your code behind:

url: "TopUp.aspx/GetCRate"

This requires a static ASP.NET AJAX Page Method to be named GetCRate, but you have this:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static OLServiceReference.CurrRate getCurr(int id)
{
    var CR = client.GetCurrRates(id);
    return CR;
}

Either change the name of your server-side method to GetCRate or change the reference in your AJAX call:

url: "TopUp.aspx/getCurr"

Upvotes: 1

Related Questions