Dynamic Sorting in Rails using AJAX

I am attempting to update a list of ideas using Ajax, but I keep encountering an unknown format error. The table structure that I am working with can be viewed here: https://i.sstatic.net/agl2R.png

My goal is to sort the table based on a specific filter option. In my home controller, I have the following code snippet:

  def sortable
    type = params[:type]
    case type
      when "Recent"
        @my_ideas = @my_ideas.ideas.sort_by(&:created_at)
      when "Less Price"
        @my_ideas = @my_ideas.ideas.order('price asc')
      when "Higher Price"
        @my_ideas = @my_ideas.ideas.order('price desc')
    end
  end

Additionally, in my JavaScript file, I have included the following script:

$('#filter_content p').on('click',function(){
    $('#filter_content').animate({
        height: 0
    }).addClass('open');
    $('#ideas .item').fadeOut().fadeIn();
    var type = $(this).text();
        $.ajax({
            url: 'home/sortable',
            type: 'GET',
            data: type,
            format: 'js'
        })
})

Initially, I tried using a respond_to block in my sortable method with format.js but it did not produce the desired outcome. Would appreciate any helpful hints or suggestions to resolve this issue.

Answer №1

Remember, the correct jQuery.ajax option to make a JavaScript request is dataType: 'script', not format: 'js'.

If you are working in Rails and want to use JavaScript as a response type, ensure you have an action that responds to JS (without a respond_to block) and a corresponding JavaScript response file like app/views/home/sortable.js.erb.

This response file, sortable.js.erb, will be sent to the browser instead of loading a new page.

After setting up your action for sorting, remember to write code within sortable.js that inserts the new HTML content into your webpage element.

For example, assuming your element is id-ed #ideas and you have a partial at app/views/ideas/_idea.html.erb:

# app/views/home/sortable.js.erb
$('#ideas').html('<%= j render @my_ideas %>')

This code snippet will render your collection using the specified partial for each idea directly into the JS code received by the browser.

With this setup, an Ajax request goes out, JavaScript comes back, and your page does not need to reload.

If this method doesn't work for you, consider avoiding AJAX altogether and simply turning your dropdown options into links leading to the same page.

Answer №2

Make sure to include the .js extension in your URL so that your response is interpreted as JavaScript code, and not just plain text.

$.ajax({
  url: 'pages/filter.js',
  type: 'GET',
  data: filterType,
  dataType: '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

Error message: It seems the spatial reference for this ESRI object is missing

Currently, I am utilizing Esri GIS to load the center location from an address. However, I am encountering an issue as I am using a geocoder from Google to obtain longitude and latitude, which is resulting in the following error message: TypeError: this.s ...

Effortless Ways to Automatically Accept SSL Certificates in Chrome

It has been quite some time that I have been attempting to find a way to automatically accept SSL certificates. Unfortunately, I haven't had any success yet. The scenario is this: I am working on selenium tests and every time I run the test on Chrome, ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

Prevent User Access from Profile

I am interested in setting up a feature to block users. I already have the button ready. <a type="button" value="1" name="block" Cursor="pointer" href="blockuser.php?uid='. $data['id'].'">Block</a> My goal is to implement ...

Using a combination of look-arounds and tag omission for advanced parsing

I am trying to identify text that is not part of another word (which I have working successfully), but I also want to ensure that the text is not inside an <a> tag. "Java <li>Javascript</li> <a href="">Some Java here</a> more ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

Saving a MongoDB document within an array in Node.js and retrieving it

I am working on retrieving specific documents from MongoDB using Node.js and storing them in an array. const getStockComments = async (req) => { const stockname = req.params.stockName; var comments = []; var data = []; const stock = await sto ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

Removing Discord Channel with Discord.js

Currently in the process of developing a ticket system using discord.js Experiencing a challenge where upon a member reacting to the message with a specific emoji, the ticket is supposed to close. However, when running the code, it is throwing an error. i ...

The JavaScript value of the button text once it has been modified

We have a website feature where the button text changes dynamically. Here are the elements before the button text change: <button _ngcontent-wex-c70="" class="btn btn-wait buy font-family-title height-70 pp-sun-ins"><labe ...

I am seeking advice on how to incorporate JavaScript to adjust slider values and add numerical values or prices. Any suggestions would

Seeking assistance with a unique project: I am currently developing a calculator that allows users to utilize sliders to select the best option for themselves across various categories. My experience with JavaScript is limited, so I decided to reach out h ...

Tips for adding additional text to c3.js Regions

Is there a way to add text to c3.js regions? I've set up three specific regions in my chart and I'd like to attach unique text labels to each of them. My attempts with d3.js have not been successful. var rectOffset = (( d3.select(this).attr("x") ...

Managing sessions and cookies for Firefox forms

On my webpage, there is a poll form where users can vote and see the results through an ajax request. When a user votes, a cookie is created to prevent them from voting again upon returning to the page. However, I have encountered an issue with Firefox wh ...

Merging object destructuring with flow-typing

Recently integrated Flow into my Create-React-App project, and while updating some of my calculation code to flow-typed, I encountered an issue with object destructuring. Here is the original signature: calcWeightOnConveyor({ tonsPerHour, conveyorLength, ...

Change background according to URL query

My goal is to dynamically change background images based on a URL parameter, specifically the destination code. With numerous background images available, it's crucial to display the correct one depending on the URL string. For instance, if the URL re ...

Trouble arises with Javascript object destructuring when used with this.props in React

Just recently I discovered object destructuring with a basic object, which worked perfectly. However, when attempting to apply it in React on this.props, all my variables are returning as undefined. I'm unsure of what mistake I might be making here. A ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

The statement ... is not a valid function, it has returned undefined

Currently experimenting with AngularJS, encountered an error message: Argument 'Controller' is not a function, got undefined View the JSFiddle link, along with HTML code: <h2>Hata's Tree-Like Set</h2> <div ng-app ng-init="N=3 ...

Should each of them be opened in a new connection if web and worker processes are separated?

In my current NodeJS web app project, there are two processes in play - a web process and a worker process. These processes communicate via AMQP. To start the application, I run two scripts: one for the web process called server.js, and another for the wor ...