Export (0) Print
Expand All

Using the AJAX Interface

Microsoft Translator's AJAX interface allows development of advanced web scenarios that deliver instant translation on specified web content quickly and efficiently. Translation can be invoked asynchronously from JavaScript running on the client-side so it does not require a full page refresh.

To use the AJAX interface you need to:

  • Obtain an Access Token on the server-side
  • Invoke the translate method on the client-side

Usage of the AJAX interface is demonstrated with a simple web application. Open Visual Studio 2010 and create a new ASP.NET web application.

Obtain an Access Token

General instructions for obtaining an Access Token can be found here: http://msdn.microsoft.com/en-us/library/hh454950.aspx

Once you have an Access Token you need to make it available to your client-side JavaScript. Place the below sample code in your Page_Load() method. The AdmAuthentication class can be found in the sample code for obtaining an Access Token.


                                    

        protected void Page_Load(object sender, EventArgs e)
        {
            AdmAuthentication admAuth = new AdmAuthentication("ClientId", "ClientSecret");
            AdmAccessToken token = admAuth.GetAccessToken();

            Response.Write(string.Format(@"
                <script type=""text/javascript"">
                    window.accessToken = ""{0}"";
                </script>", token.access_token));
        }    
									
                                

Invoke the translate method

To invoke the translate method from your client-side JavaScript you must create a script element, specify the input parameters in the URL query string, then append the script element to the document. You must specify a completion callback method with the "oncomplete=" URL parameter. Make sure to URL encode all other params as necessary.


                                    
 <script type="text/javascript">

        onload = function ()
        {
            var from = "en", to = "es", text = "hello world";

            var s = document.createElement("script");
            s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
                "?appId=Bearer " + encodeURIComponent(window.accessToken) +
                "&from=" + encodeURIComponent(from) +
                "&to=" + encodeURIComponent(to) +
                "&text=" + encodeURIComponent(text) +
                "&oncomplete=mycallback";
            document.body.appendChild(s);
        }

        function mycallback(response)
        {
            alert(response);
        }

    </script>


                                

For all available AJAX method reference

Show:
© 2014 Microsoft