1

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>

3 Answers 3

2

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

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

5 Comments

i tested that on my pc. you must be missing something.
just comment your code and copy paste the webmethod and js and make the change in the html markup onblur.
what is .time and .address here?
what if i want to call FetchAddress() on clientclick event of aspx button
@Pranav-BitWiser: if you have a question, please post
0

.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

9 Comments

And what is the difference to javascript code from OP?
still did not return anything in the textbox
@HaiderKhattak use FireBug from Mozilla for Debugging
ok i will but as far as my ajax code is concerned, is it correct...??
@You need to Declare public void getadd() as Static now updated
|
0

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;
    }

2 Comments

will autocomplete be a good idea onblur of another textbox? i think he is trying to type in a zipcode and fetch the address
I don't the exact requirement. But by this code he can get list of addresses based on zipcode. He can show in dropdown or any other way as he wants.

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.