Sending an array from JavaScript to Ruby using Sinatra

My goal is to transfer a 2D array from JavaScript to something that Ruby can interpret. All elements in the array are strings.

I have been using gon-sinatra, but it doesn't fulfill all my requirements. I tried storing the string I want to pass in 'gon.text' like this:

@temp = gon.text
array.push(@temp)

Unfortunately, this approach doesn't work because 'gon.text' appears as a nil object type instead of a string. When I try converting it using gon.text.to_s, it returns an empty string. As a result, when I attempt to display it, nothing shows up. For example,

alert("<%= @temp %>") // displays an empty string
.

I am unsure about the best course of action at this point. Would it be more effective to store the array in JSON format and then parse it in Ruby?

Answer №1

A possible solution is to first convert your array to a JSON string using Javascript:

var jsonData = JSON.stringify(yourArray);

After sending this string to your Ruby script, you can parse it back into an array using Ruby:

require 'json'

parsedArray = JSON.parse(receivedString)

Answer №2

To implement this functionality in JavaScript, you would typically write code like the following:

var myArray = [ ['str1','str2'], ['str3','str4'] ];
$.get('/endpoint', { myArray: myArray })

If you are using Sinatra as your backend framework, the corresponding endpoint code could look something like this:

get 'endpoint' do
    myArrayStr = params[:myArray]
    error!('invalid array') unless myArrayStr
    @myArray = JSON.parse(myArrayStr)
    gon.rabl 'goners/yourFile.rabl', :instance => self

In your Gon file, you can then access the data with the following reference:

alert(gon.myArray[0][0]); // str1

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

Converting a file full of JSON hashes into valid JSON using Ruby

Recently, I encountered a challenge where I received a text file from the server generated by an unalterable script. The contents of this file are formatted like "strings" of JSON data and my goal is to convert them into actual JSON using a Ruby script... ...

How to transform a JSON object into a formatted string using Vue?

I have a dynamically set JSON object that needs to be manipulated. The method onDragStop is used to set the columns: data() { return { columns: [], } }, methods: { onDragStop: function (index) { this.$set(this.columns, index, { xAxis: ...

Can you explain the concept of (A == B == C) comparison in JavaScript?

Surprisingly, the comparison I expected to fail was this: var A = B = 0; if(A == B == 0) console.log(true); else console.log(false); To my surprise, it doesn't return true. What's even more astonishing is that console.log((A == B == ...

Modify a unique custom binding handler in such a way that it is designated using an Immediately Invoked Function Expression

I am currently working on improving a custom binding handler by converting it into an Immediately Invoked Function Expression (IIFE). Despite researching IIFE online, I am still unsure of how to make the necessary changes to my custom handler. Can someon ...

The mongoose find query is coming back with an empty array, even though there is data present in the

My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection. However, I encountered an issue where the find method returns an empty array even for existing data. Here is th ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Observing input value in Popover Template with Angular UI

I am currently working on a directive that utilizes the Angular Bootstrap Popover and includes an input field. Everything seems to be functioning properly, except for the fact that the watch function is not being triggered. For reference, you can view the ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Using JavaScript, what is the best way to retrieve the provided JSON data?

Is there a way to navigate through the JSON structure displayed below? { "question":{ "119380":{ "email":{ "-L8o-zzRRTOJQjI4BQZ0":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c5c6c7e4c3c9c5cd ...

Loading Data into Spinner from sqlite database using Kotlin

I am currently working with a local database (Sqlite) and I need to retrieve all the data from one column to populate a Spinner within a fragment. I have been trying to fetch the data from the database and store it in an array to make it easier. Can anyone ...

Incorporate JavaScript .js file into the webpage asynchronously to invoke a web service

JavaScript File: JScript.js function Helloworld() { $(document).ready(function () { $.ajax ({ type: "POST", url: "Default.aspx/Helloworld", contentType: "application/json; charset=utf-8", dataType: "json", a ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Looking for a solution to my issue - my for loop is looping more times than it should

I am designing a confirm dialog using jQuery and Bootstrap. When the user clicks on 'Yes' or 'No', it should trigger an action, such as drawing two squares each time. The first time I click either button, it draws 2 squares. However, wi ...

Encountering a peer invalid error message while using npm

As I work on integrating swagger-ui into an existing project, I encounter the following error messages: Olivers-MacBook-Pro:incrementum oliverpike$ npm install --save-dev --save-exact <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

The on() method in jQuery is failing to work on an element that has a class added dynamically

After adding an active class to a link once a product is added to cart, I tried using that class to determine the function of the link. However, the on() click event on the link does not trigger unless the page is reloaded. Below is the code snippet where ...

How can I change the default selected option for a radio button in a React application?

I am having trouble setting the default checked radio button to lime in my radio button group. Even though I have set lime as the default value, it doesn't seem to work. Here is the code snippet that I am working with and I am looking for a solution ...

Tips for detecting when a browser is closing in a web application that is integrated with a master page

Currently, I am working on a web application that uses a master page. I need to be able to detect when the user is closing the browser so that I can raise an event to clean up session variables. I attempted using the unload JavaScript event, but it seems ...

What could be the reason why the angular time picker is not showing any

After using a time picker for booking and storing it in the database, I encountered an error while trying to pass the time to the input field during editing. Error: [ngModel:datefmt] Expected `01:00:00 pm` to be a date http://errors.angularjs.org/1.3.13/n ...

What is the best way to assign a series of radio buttons to an array within an Angular controller's model?

Let's say I have a controller that contains an array property named 'houses'. I want to use ng-repeat to display this array on a table row with a set of radio buttons (true/false, etc.). How can I ensure that selecting any of these radio but ...