What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table.

It seems like the variable isn't being passed to the controller.

jQuery:

var id = 1;

$.post("http://localhost:3000/teamplayers", {'ids': ids});

Teamplayers controller:

def index
   @teamplayers = Teamplayer.all
   @ids = params[:id]
end

Rails HTML:

<select id = "test3" style= float:right size= 10>
<% Teamplayer.find_each(:conditions => "teamid = @ids") do |tp| %>
    <option> <%#<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7944390d1c1814091518001c0b57'>[email protected]</a> %></option>
    <option>Players on team 1</option>
<% end %>
</select>

Also, I attempted to use the Ajax method below but it redirected my page within the designated tag.

Ajax:

$(document).ready(function(){
    $("button").click(function(){
      $.ajax({url:"http://localhost:3000/teamplayers",success:function(result){
        $('#div1').text(result);
   }});
 });
});

Where am I going wrong with my use of POST or Ajax?

Answer №1

Your main issue lies in the controller: you should be requesting params[:ids] instead of params[:id] since it is passed from jQuery as {'ids': ids}. Furthermore, ensure to include a success handler function with the $.post function to manage the response and trigger an ajax event.

Once you have correctly initialized @ids, you can directly pass it to the model's find method:

<% Teamplayer.find(@ids) do |tp| %>

This will retrieve all Teamplayers with the specified ids. Consider utilizing Rails form helpers to create the HTML select list by following this approach:

<%= select_tag "test3", options_from_collection_for_select(Teamplayer.find(@ids), "id", "name") %>

Adjust the last argument of

options_from_collection_for_select
according to your desired field from the Teamplayer table to display as text in the option tag, potentially teamid.

Lastly, it is unclear what purpose the final ajax call serves. Implementing the suggestions mentioned above should address your initial issue effectively.

Answer №2

It appears there is a minor issue with your variable naming - simply update 'id' to 'ids' where necessary:

jQuery Code Example:

var ids = 1;
$.post("http://localhost:3000/teamplayers", {'ids': ids}); 

Teamplayers Controller Logic:

@ids = params[:ids]

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

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Tips for creating a countdown timer from scratch without relying on a plugin

Looking at this image, it is clear that jQuery can be used. However, I am wondering if there is a way to create a countdown timer without relying on plugins. Can anyone offer some guidance? ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

"Why does the React useState array start off empty when the app loads, but then gets filled when I make edits to the code

I'm facing a challenging task of creating a React card grid with a filter. The data is fetched from an API I developed on MySQL AWS. Each card has a .tags property in JSON format, containing an array of tags associated with it. In App.jsx, I wrote Jav ...

data-cy appears in the DOM structure, yet remains unseen

I'm seeking some clarity on how to effectively use Cypress. While writing end-to-end tests, I encountered a failed test due to the element not being visible. A helpful answer I found assisted me in resolving this issue by clicking an element that was ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

The body parser is preventing the NODE from loading on localhost

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); //ISSUE LINE **app.use(parser.json);** /////////////// var todos = []; var nextTodoItem = 1; app.use(bodyParser.json); ap ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have: <script type="text/javascript"> ...