Construct an array through the power of Ajax

Currently, I am facing an issue with building an array using ajax. The 'test' array is structured correctly, but the 'translations' array has a flawed structure (as seen in my console output).

In Chrome console: https://i.sstatic.net/mslYm.png

In Edge console: https://i.sstatic.net/aEkV8.png

In Firefox console: https://i.sstatic.net/AhTJi.png

I need guidance on what changes to make in my code to align the structure of the 'translations' array with that of the 'test' array.

Below is the function in question:

function translateAllCaptions(dropdownId) {
var selectedLanguageValue = getDropDownSelectedLanguageValue(dropdownId);
var selectedLanguage = "";
var translations = [];
translations.push(["Caption", "Translation"]);


// Get translation language
selectedLanguageValue ? selectedLanguage = getLanguage(selectedLanguageValue) : console.log("Language dropdown error");

// Translate all captions
// Retrieve all captions
var captions = getAllCaptions();

captions.forEach(caption => {
    $.ajax({
        url: "https://www.googleapis.com/language/translate/v2",
        dataType: "jsonp",
        data: {
            key: "xxxxxxxxxxxxx",
            source: 'en',
            target: selectedLanguage,
            q: caption
        },
        success: function (result) {
            translations.push([caption, result.data.translations[0].translatedText]);
        }
    }); 
});
var test = [
    ['Caption', 'Translation'],
    ['Software', 'Logiciel'],
    ['Network', 'Réseau'],
    ['Hardware', 'Matériel']
]
// Create and download
console.log(test);
console.log(translations);
exportToCsv("Translations.csv", translations);  
}

Answer №1

When utilizing ajax requests, it's important to consider that they are initiated asynchronously. This means that the forEach function may complete before the requests are fully processed. However, when you inspect the result in the developer console, you will see that the requests eventually complete and provide the desired outcome. To address this issue, it is recommended to wait for the requests to finish before proceeding with processing the results. Although the syntax may seem cumbersome, the following approach should effectively resolve the problem:

var requests = captions.map(caption => {
    $.ajax({
        url: "https://www.googleapis.com/language/translate/v2",
        dataType: "jsonp",
        data: {
            key: "xxxxxxxxxxxxx",
            source: 'en',
            target: selectedLanguage,
            q: caption
        },
        success: function (result) {
            translations.push([caption, result.data.translations[0].translatedText]);
        }
    }); 
});

$.when.apply($, requests).then(function(deferreds) {
    exportToCsv("Translations.csv", translations);  
})

If you require the translations array to be returned from this function, a deeper dive into promises and async-await might be necessary. However, the provided solution should suffice for the purpose of exporting the data.

[Update]

In response to your feedback indicating that the solution does not work, it is likely attributed to another error in your implementation. As I lack access to your full code and API key, I have included a simple demonstration below using an API that echoes the request. Upon completion of all three requests, the results will be displayed in the console with three elements in the array.

let sources = ['blue','red','green'];
let results = [];

let requests = sources.map(color => $.getJSON(`http://mockbin.org/request?color=${color}`).then(r => results.push(r.queryString)));

$.when.apply($, requests).then(() => console.log(results));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

The date picker feature of Jquery Mobile is not appearing on the popup field

I implemented the jtsage jquery mobile date picker, and I am facing an issue where the date picker appears behind the popup instead of in front of it when the text inside the popup is clicked. Here is a snippet of my code: <div data-role="content"> ...

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ...

A guide to customizing node names using vue-slider-component

I am facing an issue with the vue-slider-component. Below is the link to my current test module: template:` <div> <vue-slider v-model="value" :order="false" :tooltip="'always'" :process="false" ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

Remove numerous entries from the WordPress database by selecting multiple checkboxes

A new customer table named "tblvessel" has been created in the Wordpress database. The code provided below selects records from the database and displays them as a table with checkboxes next to each record, assigning the record's 'ID' to the ...

Prepare JSON formatting for retrieving external data with Select2

I am attempting to implement the Select2 example for loading remote data, but I am struggling to understand the correct json format it should have. Here is the example code I am using: $(".js-data-example-ajax").select2({ ajax: { url: "http://l ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

Troubleshooting the display of API-generated lists in Angular 8

I am encountering an issue in Angular 8 when trying to display my list on a page. Below is the code from my proposal-component.ts file: import { Component, OnInit, Input } from "@angular/core"; import { ActivatedRoute, Params } from "@angular/router"; imp ...

The JSX function seems to be malfunctioning, as the function part is not displaying on the webpage as intended

This code snippet is a part of a React component in a project. I have imported a CSS file for styling and have already integrated Material UI. However, the function for the new article is not displaying on the webpage as expected. import "./Widgets. ...

Is there a way to use grease/tampermonkey to automatically redirect the current definition from Dictionary.com to Thesaurus.com?

Is there a way to use Greasemonkey or Tampermonkey to automatically open the definition on Dictionary.com at Thesaurus.com, and vice versa, when clicking specific links? (Shown in red) My initial thought is to retrieve the word being searched from the URL ...

Using gmaps4rails: A guide on extracting JSON data from the controller

I have a model named shop and I want to create a simple alert box using JavaScript that shows the name of the shop when a marker on the map is clicked. Here's my code: # controller @json = Shop.all.to_gmaps4rails do |shop, marker| marker.json({ id ...

iOS unique identifier with Phonegap and AngularJS

I'm working on an AngularJS and PhoneGap app, and I need a way to generate a unique identifier for each user of the app. It seems like getting the phone number from the device is not possible, can anyone confirm this? If retrieving the phone number ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...