Encountering an issue when attempting to use AJAX for displaying a partial code on the current page

I'm a beginner with Rails and my current project requires me to load a specific element on the same page without affecting other elements. To achieve this, I created a new route in routes.rb as follows:

get "/sell_used_car/edit", to:"sell_used_car#edit", as: :sell_used_car_edit

The view of the page located at "views/sell_used_car/new.html.erb" looks like this:

  <%= link_to "Change Email", sell_used_car_edit_path, remote: true %>
  <div id = "content"></div>

In the sell_used_car_controller.rb file, I have included the following code:

def edit
    respond_to do |format|
        # format.html{}
        format.js
    end
end

When I uncommented the line format.html{}, I encountered an error stating: "SellUsedCarController#edit is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []"

If I kept that line commented out, I received an error saying: "ActionController::UnknownFormat"

I've made sure that the files edit.js.erb and _edit.html.erb are placed correctly. Here's how they look:

edit.js.erb

$('#content').html("<%= escape_javascript(render :partial => 'edit')%>");

_edit.html.erb

<%= form_with do |form| %>
<div class="d-flex align-items-center justify-content-center flex-column">
<div class="mb-3">
    <%= form.label :Enter_Your_New_Email%>
    <%= form.text_field :email,  placeholder: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2cacbc8f2d3d0d19cd1dddf">[email protected]</a>", class: "form-control"%>
</div>
</div>
<%end%>

I understand that including the line format.html{} causes an error because it cannot find the .html.erb file even though it should render to a partial file according to my edit.js.erb. Despite only using the code in the controller like this:

def edit
    respond_to do |format|
        # format.html{}
        format.js {render :edit}
    end
end

The same error persists as "ActionController::UnknownFormat". I'm really stuck here.

Appreciate any help in advance.

Answer №1

When using the standard link_to method, you are sending a HTML request which is displayed in the console as

Processing by SellUsedCarController#edit as HTML
.

In order to make an AJAX request in Rails, you need to have rails-ujs installed and add format: :js in your link_to tag. For more information on this topic, check out Rails link_to with remote: true processing html instead of js after page refresh.

If you are using a newer version of Rails, you can convert your link_to into a button that triggers a fetch call via JavaScript or utilize Turbo to dynamically change the content for you.

Here's an example using a JavaScript AJAX call:

<button onclick="renderChangeEmail()">
Change Email
</button>

<div id = "content"></div>

<script>
  const renderChangeEmail = () => {
    $.ajax({
      beforeSend: function (xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
      },
      url: '<%= sell_used_car_edit_path %>',
      remote: true,
      dataType: 'script',
      type: 'get',
    })
  }
</script>

Answer №2

After double-checking multiple times, I confirmed that jQuery was properly installed. However, the root of the issue, as mentioned in my previous comment, was in the manifest.json file that I had manually created. This resulted in the absence of the "public/packs/js" folder. To resolve this, I manually created the folder and placed both the "application-e421b4aa3f716bebdab1.js" and "application-e421b4aa3f716bebdab1.js.map" files inside it. Now everything is functioning perfectly.

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

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

Converting JSON to CSV using Node.js

Looking to convert JSON data to a CSV file in Node.js? Wondering if there are any predefined modules for this task? P.S. Additionally, interested in incorporating formatting such as including headers like "MONTHLY REPORT" and row colors? ...

What is the best way to allocate inner JSON to an object within a promise?

Exploring the Angular2 tutorial "Tour of Heroes" showcases how to handle JSON data within a promise. But what if the JSON structure is more complex? JSON: let complexMessage = [{ "heroes":[ {id: 11, name: 'Mr. Nice'}, {id: 12, ...

Changing the close button icon in highslide popups

Utilizing highslide together with highcharts, I need to customize the functionality of the close button. Specifically, I want to trigger an additional function when a user clicks on the "X" button. Upon inspecting the "X" button, this is what appears in m ...

combine numerous functions to ajax response success

Can multiple ajax functions be bound to an ajax success call? For example, consider the following code: $('#deals').each(function() { var city_slug = $(this).data('city'); $(".dealloader").show(); //load de ...

What is the method for resetting the counter back to 1 whenever the labels are updated?

I am currently working on a breathing exercise code that involves counting in the following manner: 8-second inhale 8 second "hold inhale" 12-second "exhale" 8-second "hold exhale" Everything is functioning correctly except for the counter, which con ...

Errors are being displayed in the console when attempting to use Vuex getters in a component. This is happening because the Vuex state properties are still null at the time the getters

When assigning results from GET requests to my Vuex state properties, it's expected that they won't be available instantly. However, I have a getter like the following: findChampion: (state) => (id) => { let championId = id.toString() ...

Error encountered while using $.each: Unable to utilize 'in' operator to search for '37' within the context

My JSON Object structure is as follows : var jsonData = "{'key1' : 'value1', 'key2' : 'value2'}"; Since it's already in JSON format, parsing isn't necessary. I simply want to loop through the object using ...

Can you explain the meaning of `suppressed_by_user` in Google One Tap?

When the user clicks sign in, I want the one tap to appear. The code below works fine when it runs as soon as the page loads. However, if I try to run it on click, I get the error suppressed_by_user. I do not have an ad blocking plugin enabled and I am uns ...

What steps can I take to ensure my website is mobile-friendly?

My website isn't displaying correctly on cellphones. According to the tutorial I'm following, it should look like this: https://i.sstatic.net/XNDfQ.png However, this is how it appears on my Samsung Galaxy S5: https://i.sstatic.net/veHTP.png I ...

What is the best way to extract ABC 12005 from strings like ABC000012005 and ABC0000012005?

My task involves parsing a string with values like ABC000012005,ABC0000012005. The desired output is to extract the prefix and numbers without leading zeros, formatted as ABC 12005, ABC 12005 ...

I am trying to utilize a cookie to retrieve the current month, date, and time. Unfortunately, the information is not displaying properly and the date is showing up as

I'm facing an issue with the code snippet below. I keep receiving an undefined error in this specific line of code: `var datemsg = nameOfMonths[date.getMonth()] + " " + date.getDate();`. When I simply use var date = new Date();, the values are succes ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Having trouble with Socket.io sending data to a specific socketId?

I'm currently using Socket.Io 1.7.3 with Angular 2, connecting to a ExpressJS Server. I'm facing an issue where I am unable to send packages to a specific socket ID even though they are a match. Server code snippet: socket.on('subscribeNot ...

Exploring JSON Parsing with jQuery

My API returns the following JSON: {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"cost": 1000, "amount": "$10 Gift Card", "id": 2, "resource_uri": "/api/amount/2/", "slug": "10-gift-card"}]} While I a ...

Angular: creating a template with a directive inside another directive

Let me share a simple example... Here is the code snippet: angular .module('app', []) .directive('parentDirective', parentDirective) .directive('childDirective', childDirective); function parentDirecti ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

Choosing the initial radio button in ng-repeat for validation purposes

Angular1 I have implemented the code snippet below to automatically select the first value in the result set if it is not already selected. Take a look at "$index==0?true:false" HTML <li ng-repeat="address in addresses | filter:vm.addressSearch"> ...

Adjust the width of child elements based on their content in order to fill the entire width of the container

I have a navigation menu consisting of 9 items. I want each item to have a width that adjusts to the content plus padding, so they can fill the full width of the parent element. Additionally, I need it to be responsive at specific widths. How can I achieve ...