Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id.

The objective: Setting up the correct route for AJAX and Rails.

What I require: The format articles/1/comments/2.

Main goal: To specifically load comment through AJAX, not article.

In the current AJAX script below, the variable undefined is noted as article_id, which has been defined as follows:

  var getArticle = function () {
    return $('.article-title').each(function() {
      var article_id = $(this).data('article-id');
  });
};

$(document).ready(getArticle);

AJAX Request:

 var loadComment = function() {
  return $('.comment-content').each(function() {
    var comment_id = $(this).data('comment-id');
    return $.ajax({
      url: "/articles/" + article_id + "/comments/" + comment_id,
      type: 'GET',
      dataType: 'script',
      error: function(jqXHR, textStatus, errorThrown) {
        return console.log("AJAX Error: " + textStatus);
      },
      success: function(data, textStatus, jqXHR) {
        return console.log("Success!");
      }
    });
  });
};

$(document).ready(loadComment);

$(document).on('page:change', loadComment);

Index:

  - @articles.each do |article|
    %article-title{ :class => "article-title", "data-article-id" => article.id }= article.title
    - article.comments.each do |comment|
      %comment-content{ :id => "comment-#{comment.id}" }

Answer №1

Include the following code snippet in your routes.rb:

resources :posts do
  resources :comments
end

Additionally, create a new controller as shown below:

class CommentsController < ApplicationController
  def display_comment
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    render json: @comment
  end
end

By making a request like this:

curl http://localhost:3000/posts/123/comments/456.json

You'll have access to params[:post_id] with a value of 123, and params[:id] with a value of 456. The id parameter is meant to represent the comment's ID.

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

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

What is the process for transforming the result of a .aspx file into a JSON format?

I am trying to convert the output of an .aspx page into a JSON object in order to accommodate a JSONP Ajax request. Here is what's happening on the page: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="mypage.aspx.cs" Inherits="folder_myp ...

Comparing Two Arrays in AngularJS and Disabling on Identical Cases

I currently have two tables: "Available subject" and "Added subject" which are populated by ng-repeat with two separate lists of objects. My objective is to accomplish three things: 1 - When the user clicks on the plus sign, a row with identical content s ...

Does the value obtained from a dropdown list change only once?

I have implemented a jQuery Ajax function to pass a value as a parameter to my controller, and receive HTML data back to update my cart table. $(document).ready(function () { $(".Quantity").change(function () { var ProID = $(this).attr("data" ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...

Switching Next.js route using pure JavaScript

Currently, I am facing a challenge in changing the route of a Next.js application using vanilla Javascript. In order for the code to be compatible with Chrome Dev Tools, I cannot dynamically change the route with Next.js and instead must find a solution us ...

Encountering a Laravel Axios error when using Vue: status code 419 issue

Issue: When users interact with my application by posting questions, I am encountering a problem. Upon clicking the Ask button to submit the question using Vue.js and Axios, about 70% of the time the submission is successful. However, approximately 30% of ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

Using AJAX to send a request with an image to a Spring MVC controller

I am attempting to utilize AJAX to send an image: function uploadImage() { var image = document.getElementById('image').files[0]; var formData = new FormData(); formData.append('image', image); $.ajax({ url: &ap ...

Concealing the submit button until a file has been selected

How can I make the submit button invisible until a file is selected? <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="imageURL[]" id="imageURL" /> <input type="submit" value="submi ...

While PHP confirmed it to be true, Jquery AJAX contradicted and said it

Currently, I am in the process of developing an application that requires checking for the existence of a product. To achieve this functionality, I opted to utilize jQuery due to its user-friendly nature. However, I have encountered some challenges in veri ...

Having trouble with functions in jQuery Ajax calls to ASMX files

I have a form in my web application that submits data through an ajax call to an asmx web service. The insertion of data into the database is successful, however, neither the success nor error function seems to be triggered afterwards. The first alert mess ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...