"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered.

Below is the code snippet:

function updateContent() {
  $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>');

  $('.houses').html('
    <% if @houses.count > 0 %>
      <%= escape_javascript render(@houses) %>
    <% else %>
      <%= escape_javascript '<div class="message-box"><p>No houses matching those parameters</p></div>' %>
    <% end %>
    ');
  $('.paginator').replaceWith('<%= escape_javascript(render("shared/house_paginator").to_s) %>');
}

I suspect that this approach might not be the most appropriate. Could someone suggest a better solution?

If you have any insights, please share them. Thank you!

Answer №1

<% if @houses.count > 0 %>
  <% result = render(@houses) %>
<% else %>
  <% result = '<div class="message-box"><p>No houses matching those parameters</p></div>'.html_safe %>
<% end %>

function updateContent() {
  $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>');

  $('.houses').html('<%= escape_javascript(result) %>');
  $('.paginator').replaceWith('<%= escape_javascript(render("shared/house_paginator").to_s) %>');
}

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

JavaScript for controlling first-person movement with a mouse

Currently, I am working on implementing a first person movement feature using the mouse. While I have successfully implemented it using the keyboard, I am facing challenges with the mouse input. The issue arises from the ambiguity in movement directions ca ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Options for jquery UI autocomplete only appear after the second search

Here is the code snippet I am working with: $("#hifind-find").keyup(function(){ var val = $(this).val(); if (val.length > 1) { var posturl = '/hifind/jquery_ui/autocomplete/'+val; $.post(posturl, function(r) { $("#hifin ...

Utilizing d3.js to filter a dataset based on dropdown selection

I am working with a data set that contains country names as key attributes. When I select a country from a dropdown menu, I want to subset the dataset to display only values related to the selected country. However, my current code is only outputting [obje ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

unleashing the magic of AJAX: a guide to extracting

In my Symfony project, I am attempting to retrieve the content of an AJAX request in order to check the data using dump(). The purpose is to process this data and perform a SQL query. However, when I use dump() in my controller, there doesn't appear t ...

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...

The POST value has been identified in the raw post data, but it is not present within the php $_

Here is my unprocessed post data: ------WebKitFormBoundaryXQrRmAvDBGudXqzO Content-Disposition: form-data; name="cmd" update_cars_item ------WebKitFormBoundaryXQrRmAvDBGudXqzO Content-Disposition: form-data; name="john_id" 30 ------WebKitFormBoundaryXQr ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop. $(... + '<div class="recommendations filter" id="recCards-'+ i +'">' + &apo ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

SMTPConnection._formatError experienced a connection timeout in Nodemailer

Our email server configuration using Nodemailer SMTP settings looked like this: host: example.host port: 25 pool: true maxConnections: 2 authMethod: 'PLAIN' auth: user: 'username' pass: 'pass' We encou ...

Retrieve element attributes and context inside a function invoked by an Angular directive

When working with a directive definition, you have access to the $element and $attrs APIs. These allow you to refer back to the element that called the directive. However, I'm curious how to access $element and $attrs when using a standard directive l ...

Executing a serverless function in Next.js using getStaticPaths: A step-by-step guide

In my current project, I am utilizing Next.js and the Vercel deployment workflow. To set up page generation at build time, I have been following a guide that demonstrates how to generate pages based on an external API's response. // At build time, t ...