Haider Khattak
Haider Khattak

Reputation: 577

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.

The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.

The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.

Code-Behind

public void getadd()
{
    string address = "";
    //_Address.InnerText = _PostCode.Text;
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
    XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
    if (distanceX.Count > 0)
    {
        address = distanceX[0].InnerXml;
        TextBoxPicAddress.Text = address;
    }
}

JavaScript

<script type="text/javascript">
    function submit() {
        $.ajax({
            type: "POST",
            url: "Establishment_Controller.aspx.cs/getadd",
            data: dataValue,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',

            success: function (result) {
                alert("We returned: " + result.d);
            }
        });
    }
</script>

Markup

<asp:TextBox ID="TextBoxPicPostCode" runat="server" 
    CssClass="time" 
    onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server" 
    CssClass="address">
</asp:TextBox>

Upvotes: 1

Views: 1360

Answers (3)

codeandcloud
codeandcloud

Reputation: 55210

Make these changes

JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
    // change the function name from 'submit' here and at markup
    function FetchAddress() {
        //passing postalCode as string. 
        //Make sure that 'postalCode' is the parameter name at the webmethod
        var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
        //would be worthwhile to read about JSON.stringify, its the standard method
        //var dataValue = JSON.stringify({ postalCode: $(".time").val() });
        $.ajax({
            type: "POST",
            url: "Establishment_Controller.aspx/getadd", // .cs is not required
            data: dataValue,
            contentType: 'application/json', //charset is not required
            //dataType: 'json', // not required
            success: function (result) {
                var data = result.hasOwnProperty("d") ? result.d : result;
                //alert("We returned: " + result.d);
                // now we are assigning the return value to TextBoxPicAddress
                $(".address").val(data);
            }
        });
    }
</script>

Code-behind

//1. webmethod attribute required
[System.Web.Services.WebMethod] 
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed 
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
    string address = "No Address found!";
    //_Address.InnerText = _PostCode.Text;
    XmlDocument xDoc = new XmlDocument();
    var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
        + postalCode + "&sensor=false";
    xDoc.Load(remoteXml);
    XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
    if (distanceX.Count > 0)
    {
        address = distanceX[0].InnerXml;
    }
    return address;
}

At markup, change the event as onblur="FetchAddress();"

P.S: No time to type all the changes made in detail, so added as comment

Upvotes: 2

Darshan Jadyal
Darshan Jadyal

Reputation: 74

HTML

Javascript `

    function danish() {
        var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();

        $.ajax({
            type: "POST",
            url: "GoogleAPI.aspx/getadd",
            contentType: 'application/json; charset=utf-8',
            data: '{code: "' + code + '"}',
            dataType: 'json',
            success: function (result) {
                $("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
            }
        });
        return false;
    }

</script>`

Codebehind

using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

[WebMethod]
    public static List<string> getadd(string code)
    {
        string address = "";
        List<string> lst = new List<string>();
        XmlDocument xDoc = new XmlDocument();
        var jsonSerialiser = new JavaScriptSerializer();

        try
        {
            HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
            xDoc.Load(@"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
            XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
            if (distanceX.Count > 0)
            {
                for (int i = 0; i < distanceX.Count; i++)
                {
                    lst.Add(distanceX[i].InnerXml);
                    address = address + distanceX[i].InnerXml;
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return lst;
    }

Upvotes: 0

Dgan
Dgan

Reputation: 10285

.cs is Not Required and

public void getadd()

Should be Static so

[System.Web.Services.WebMethod]
public static void getadd()

JScript

<script type="text/javascript">

                            function submit()
                            {
                                $.ajax({
                                    type: "POST",
                                    url: "Establishment_Controller.aspx/getadd",
                                    data: dataValue,
                                    contentType: 'application/json; charset=utf-8',
                                    dataType: 'json',

                                    success: function (result) {
                                        alert("We returned: " + result.d);
                                    }
                                });
                            }

                        </script>

EDIT: You Can't Use Controls Inside Static method. You nee to Refer This:

Using Jquery Ajax Call

Using AutoCompleteExtender

Upvotes: 0

Related Questions