0

I use the following code from this Google Translate API's Get Started

  <head>
    <title>Translate API Example</title>
  </head>
<body>
  <div id="sourceText">Hello world</div>
  <div id="translation"></div>
  <script>
  function translateText(response) {
    // ERROR SHOW HERE
    document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
  }
  </script>
  <script>
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    var sourceText = escape(document.getElementById("sourceText").innerHTML);

    var source = 'https://www.googleapis.com/language/translate/v2?key=MY-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
    newScript.src = source;

    // When we add this script to the head, the request is sent off.
    document.getElementsByTagName('head')[0].appendChild(newScript);
  </script>
</body>

And I get the error "TypeError: Cannot read property 'translations' of undefined"

Please tell me how to fix this error,

Thanks,

Sebastian Kreft
  • 7,819
  • 3
  • 24
  • 41
Huy Tower
  • 7,769
  • 16
  • 61
  • 86

1 Answers1

0

I received the message from someone who tell me how to fix this error,

I think I was able to replicate your error, but only once - the example works for me, in a variety of translated languages and so on. I thought I saw the error just once, before I had my Chrome developer console running. I did try adding console.log(response) to the translateText() callback, but that also has not shown the bug again. Try seeing what you can log at // ERROR SHOW HERE in your sample.

Of course, the example in the documentation is extremely brittle code — I can imagine there are circumstances where the data member isn't present, only an error. e.g.:

// API callback
translateText({
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid Value",
    "debugInfo": "Target language is not set to a valid language code:…\n"
   }
  ],
  "code": 400,
  "message": "Invalid Value"
 }
}
);

And, it's really good,

Need add "console.log(response)" as below code :

<script>
function translateText(response) {
console.log(response);
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;

}

Thanks,

Community
  • 1
  • 1
Huy Tower
  • 7,769
  • 16
  • 61
  • 86