Function not currently in operation

There seems to be an issue with the script not running or returning any answers. The console is blank. I am attempting to retrieve an answer from the Yandex Translate site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) Code: http://jsbin.com/jolijep/edit?html,js,console,output

var app = angular.module('jsbin', []);

app.controller('DemoCtrl', function($scope, $http) {
  var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
  keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";
  var vm = this;
  $scope.SendData = function() {
    // Data to be sent
    var textApi = 'Hello';
    var langApi = 'en-ru';
    var data = "key=" + keyAPI + "&text=" + textApi + "&lang=" + langApi;


    $http.post(url, data)
      .success(function(data, status, headers, config) {
        vm.data = response.data;
        $scope.PostDataResponse = data;
        console.log(data);
      })
      .error(function(data, status, header, config) {
        $scope.ResponseDetails = "Data: " + data +
          "<hr />status: " + status +
          "<hr />headers: " + header +
          "<hr />config: " + config;
      });
  };
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Angular JS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="weather.js"></script>
</head>

<body ng-app="jsbin">
  <div ng-controller="DemoCtrl as vm">
    <script src="weather.js"></script>
    <button ng-click="SendData()">Send</button>
    <br>Data: {{PostDataResponse}}
    <br>{{vm.data}} {{vm.PostDataResponse}} Data: {{scope.PostDataResponse}} {{vm.data}}
  </div>
</body>

</html>

Answer №1

When referencing the Yandex translate API documentation, it specifies that information for a request must be passed as parameters appended to the request URL.

An alternative method of retrieving data from an API through a POST request involves passing information in the body of the request.

However, the Yandex translate API requires information to be attached to the URL when using a POST request.

var data = "key="+keyAPI+"&text="+textApi+"&lang="+langApi

The above data variable should be added to the url variable when sending a POST request to the API. However,

$http.post(url, data)

Using the $http method causes the data to be interpreted as the body of the post request instead of being appended to the url during the call.

A more efficient approach with the AngularJS $http API would involve placing all parameters inside an object where keys represent parameter types and values denote parameter values.

var params = {
      key: keyAPI,
      text:textApi,
      lang:langApi
}

Now, the params object holds all the necessary information for the request.

Additionally, the $http request needs modification to specify which params are to be added to the url. Using a basic $http method instead of $http.post, specify the base url, HTTP request method, and the required params.

$http({
   url: url,
   method: 'POST',
   params: params
})
.success(function(data,headers,status,config){
  $scope.PostDataResponse = data;
  vm.data = data;
  console.log(data);
 })
.error(function(data,headers,status,config){
 $scope.ResponseDetails = "Data: " + data +
                "<hr />status: " + status +
                "<hr />headers: " + header +
                "<hr />config: " + config;
});

One issue in the code was how $scope.PostDataResponse was initialized.

 $scope.PostDataResponse = response.data; //There is no 'response' argument passed to the success function

The correct way to do this is $scope.PostDataResponse = data;

After implementing these modifications, the code should run smoothly.

If everything is set up correctly, you will see an object logged in the developer console upon a successful request.

Object showcasing successful call message

Your webpage will also display the same object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...

Issue with Element.update() method malfunctioning on IE browser is causing concern

Utilizing the Element.update() method from the prototype: [ ... ] var link_1 = new Element('a').update( '<' ); var link_2 = new Element('a').update( '<<' ); [ ... ] Encountering a unique issue only in IE: ...

The tooltip function is not functioning properly on Internet Explorer when the button is disabled

I have been utilizing a similar solution found at http://jsfiddle.net/cSSUA/209/ to add tooltips to disabled buttons. However, I am encountering an issue specifically in Internet Explorer (IE11). The workaround involves wrapping the button within a span: ...

Executing the linker function exclusively following the completion of template parsing

Currently, I am developing an AngularJS directive that utilizes a bootstrap plugin for implementing "checkbox switches". In my implementation, the plugin initialization occurs within the link function of the directive. However, it appears that this functi ...

Remove bulleted list from HTML using JavaScript DOM

My task involved deleting the entire "agent" array using the removeChild() function, requiring the id of a <ul> element. However, I faced an issue as I couldn't set the id for the "ul" due to using the createElement() function. //old code < ...

React doesn't properly display JSON data

I am facing an issue with the code below that is supposed to display data from a JSON file. Instead of showing the desired data, it only displays the h1 with curly braces. Here is the faulty code: import prod from "../../data/produtos.json"; exp ...

Can express-handlebars tags be utilized within an HTML script tag when on the client side?

For a while now, I've been facing a challenge. I'm in the process of building an application with express-handlebars and so far everything is going smoothly. The data that needs to be displayed on the webpages looks good thanks to the Helper func ...

How would you go about creating a VueJS component that displays a table with a set number of columns and automatically distributes the cells within them?

Hey there! I'm currently working with a VueJS component that looks like this: <template> <div> <table> <tbody> <tr v-for="(item, index) in items" :key="index"> <t ...

What is the process for altering a route in React 18?

Previously, I relied on the withRouter Higher Order Component (HOC) along with props.history.push() function to manage routes. However, with the introduction of React 18, these options are no longer available. My current task involves editing a post and ...

Following the submission of a message, the textarea automatically inserts a line-break

Can someone please help me troubleshoot an issue with my chat app? Every time I try to send a message, the textarea adds a line break instead of just focusing on the textarea so I can send a new message smoothly. I have recorded a video demonstrating the ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Tips on effectively centering a wide div

After much experimentation, this is what I came up with: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en ...

Creating a structure object in a Laravel controller for implementing Vue.js autocomplete functionality

I am currently facing an issue with my autocomplete feature not displaying options correctly. To start off, I am fetching hard coded data from my controller and passing it through an axios call: searchController.php $searchResults = [ 0 => (ob ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

Tips for ensuring my data remains protected when navigating back using the browser's back button

How to Preserve API Call Response Data on Browser Back Button Click with reloadOnSearch Set to false By setting reloadOnSearch to false, I am utilizing $routeUpdate to detect browser back button clicks. Currently, the page gets reloaded upon this event, c ...

Execute the validation directive using the digest cycle

This particular directive is designed to determine whether a given value exists within the associated datalist or not. It functions flawlessly when I input text into the field, but it fails to work properly if the datalist undergoes changes as a result o ...

Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue: The expected output should resemble: [ {first:"John", last: "Smith", id: ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

To properly handle this file type in React, ensure you have the correct babel loader installed

https://i.sstatic.net/iNFs3.pngAn error is triggered when trying to compile with webpack. The message indicates that an appropriate loader may be needed to handle this file type. The libraries I am using are: https://i.sstatic.net/a8fXR.png Below are my ...