Why isn't my AJAX post in Rails working with a partial JS.slim template?

I'm working on a Rails application similar to a comments board and I want to incorporate ajax functionality. However, my code is not functioning as expected and I can't seem to pinpoint the issue...

Here is the code from my controller:

# controller/article_controller.rb

def show
  @comments = Comment.where(article_id:params[:id])
end

def comment
  @comment = Comment.new(comment_params)
  respond_to do |format|
    if @comment.save
      @comments = Comment.where(article_id:params[:id])
      format.js
    else
      render 'show'
    end
  end
end

private
  def comment_params
    params.require(:comment).permit(:comment)
  end 

The corresponding view looks like this:

views/article/show.slim

= form_for(@comment, url: comment_path, data: { remote: true }) do |f|
    = f.text_area :comment
    = f.submit 'create'

#board_comments
  = render partial: 'comment', locals: { comments: @comments }

For the partial template in views/article/_comment.slim:

- comments.try(:each) do |comment|
  p = comment[:comment]

The JavaScript file views/article/comment.js.slim contains:

| $('#board_comments').html("#{j render(partial: 'article/comment', locals: { comments: @comment }) }");
| $('#comment_comment').val('');

Can anyone help identify what may be causing the issue in my code?

Some relevant logs:

Started POST "/article/9/comment" for 127.0.0.1 at 2014-08-04 00:31:05 +0900
Processing by ArticleController#comment as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FJYVadfpYoZc7OPdk68guKxiPLKdYb2LkQJfKVKRZw=", "comment"=>{"comment"=>"1234"}, "commit"=>"create", "id"=>"9"}
(0.5ms)  BEGIN
SQL (6.3ms)  INSERT INTO `comments` (`comment`, `created_at`, `updated_at`, `user_id`, `article_id`) VALUES ('1234', '2014-08-03 15:31:05', '2014-08-03 15:31:05', 1, 9)
(2.2ms)  COMMIT
Comment Load (0.5ms)  SELECT `comments`.* FROM `comments`  WHERE `comments`.`article_id` = 9
Rendered article/_comment.slim (1.0ms)
Rendered article/comment.js.slim within layouts/application (38.0ms)
Rendered shared/_menu.html.slim (1.9ms)
Rendered layouts/_ga.slim (0.3ms)
Completed 200 OK in 213ms (Views: 159.1ms | ActiveRecord: 9.5ms)

The layout file views/layouts/application.slim includes:

doctype html
html
  head
    = stylesheet_link_tag 'application', media: 'all'
    = javascript_include_tag 'application'
    = favicon_link_tag('favicon.ico')
    = csrf_meta_tags

  body
    = render 'shared/menu'
    = yield
    = render 'layouts/ga'

Answer №1

When examining this line within your views/article/comment.js.slim:

$('#board_comments').html("#{j render(partial: 'article/comment', locals: { comments: @comment }) }");

The issue lies in passing @comment as comments in the partial, where the partial includes:

- comments.try(:each) do |comment|
  p = comment[:comment]

However, based on the line locals: { comments: @comment } comments only holds newly created comments and does not contain all comments. Thus, adjustment is needed in your js.slim file to:

$('#board_comments').html("#{j render(partial: 'article/comment', locals: { comments: @comments }) }"); // please note it's @comments instead of @comment

Answer №2

If you are still looking for a solution, or if someone else comes across the same issue. I recently faced a similar problem and after reaching out on Stack Overflow, I found that adding

{ render layout: false, content_type: 'text/javascript' }
right after format.js resolved the issue.

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

Extract values from HTML IDs and store them in an array

Currently, I am working on a project where I need to capture a QR code and display it on the screen. After that, I want to iterate through the elements using a for loop and save the values in an array. Specifically, I am using the ID id="scanned-resul ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Creating and deleting HTML elements in a dynamic array format

My current approach involves utilizing jQuery and JavaScript for the purpose of dynamically adding and removing HTML elements. Specifically, I am focusing on the removal of particular HTML elements. The code snippet is as follows: $(document).ready(fun ...

Automatically enlarge the container when the text area contains text

I am currently developing a blog using PHP / MySQL and have successfully implemented an edit post function. Upon clicking the "Edit" button, the page refreshes (URL changes), the <div> expands, and the content of the post being edited is displayed i ...

Get the value of the button that has been clicked

I have a query regarding building a website that can be started via PowerShell. The PowerShell HTML code I am using is: $proxys = "" foreach ($email in $ADObj.proxyAddresses){ $proxys += "<button id='$email' name='alias&apo ...

Incorporating an unique identification code within the input field

I have a HTML code that displays geolocation information: <span id="currentLat"></span>, <span id="currentLon"></span> When combined with JavaScript, it works perfectly. However, I am trying to display the above value in a text fi ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. https://i.sstatic.net/8tdfV.png The shifting dot in each imag ...

What methods are available to trigger an AutoHotkey script using JavaScript?

I'm in the process of creating a Chrome extension designed to streamline tasks. I've come to a stage where I require my extension to execute certain AutoHotkey scripts. Is there a method to execute an AutoHotkey script using JavaScript? (I' ...

Steps for automatically closing a TextPrompt if the end user does not respond within a specific time frame

How can I programmatically close a Prompt in Microsoft Chatbot SDK v4, such as TextPrompt or ConfirmPrompt, and end the dialog after a certain period of time if the user does not reply? I attempted to use setTimeout and step.endDialog but encountered issu ...

Troubleshooting: Issues with jQuery JavaScript Modal Popup functionality within MVC framework

When I click on the "Comments" link, a modal popup opens up and displays the content as expected. Now onto my issue: In the first scenario, the desired outcome is achieved but some other code does not execute. In this case, when I place the "@section" ins ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

Utilize the `addEventListener` and `removeEventListener` functions on the menu to

Why is my mobile menu not functioning correctly? The submenu should open on the first click and redirect to the parent URL on the second click, which works fine. However, when the window width increases to 768px or more, the submenu should appear on hover ...

What is the best way to define a constant within a map function?

I have a VueJs computed function called linhas() that populates the rows of my DataTable. I am struggling with opening up this function to assign a value to "this.grupo", so that I can avoid using it the same way as I do with "this.maquinas". As a beginner ...

Determine if the content has finished loading once it has been added using JavaScript

I am currently working on a project in pure JavaScript that involves implementing a feature similar to Facebook's message loading. This means that when you scroll to the end of the page, new HTML content is loaded and added to the page. The additional ...

How come the link function of my directive isn't being triggered?

I'm encountering a strange issue with this directive: hpDsat.directive('ngElementReady', [function() { return { restrict: "A", link: function($scope, $element, $attributes) { // put watche ...

retrieve data from jsp page using ajax request

I've coded this JSP snippet Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulate ...

Ng-Zorro nz-range-picker resizing issue on smaller mobile screens

Currently using ng-zorro-antd 7.0.0 rc3 alongside angular 7.2.4. Encountering an issue where horizontal scrolling is not possible on mobile browsers when using the nz-range-picker. It appears that the element is too large for the screen, even though the p ...

Show a confirmation dialog box using bootbox that includes a link when the user selects OK

I am currently experimenting with integrating bootbox.js into a test page. However, I am facing an issue where the href tag in the hyperlink triggers regardless of whether the user selects the Cancel or OK button on the bootbox. Is there a way to include ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...