Is there a way to dynamically insert the user's id into the URL section of an AJAX request?

Seeking to make the '2' in the url field of the getEvents function dynamic by replacing it with the current user's id.

I was thinking of using ${current_user.id}. Can someone guide me on how to achieve this? Ideally, I'm aiming for something like:

function getEvents() {
  $.ajax({
    url: 'http://localhost:3000/users/`${current_user.id}`/events',
    method: 'get',
    dataType: 'json'
  }).done(function(data) 

I have a current_user method in my ApplicationController file. I attempted applying json but encountered errors. Here is the complete code:

 class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  helper_method :current_user, :logged_in?, :log_user_in #let these methods be used in views

  private
  def log_user_in
    session[:user_id] = @user.id
  end

  def logged_in?
    !!current_user
  end

  def current_user #should return previous user or look for current user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
  end

$(function() {
  console.log('event.js is loaded...')
  listenForClick()
});

function listenForClick() {
  $('button#events-data').on('click', function(event) {
    event.preventDefault()
    getEvents()
  })

  function getEvents() {
  $.ajax({
    url: 'http://localhost:3000/users/2/events',
    method: 'get',
    dataType: 'json'
  }).done(function(data) {

    console.log("the data is: ", data)
    debugger
    let myEvent = new Event(data[0])
    let myEventHtml = myEvent.eventHTML()
    document.getElementById('ajax-events').innerHTML += myEventHTML
  })
}


class Event {
  constructor(obj) {
    this.id = obj.id
    this.name = obj.name
    this.host = obj.host
    this.description = obj.description
    // this.host.user.id = obj.user.id
  }
}


Event.prototype.newEventForm = function() {
   (`
  <strong>New Event</strong>
  <form>
    <input id='event-name' type='text' name='name'></input><br>
    <input type='text' name='description'></input><br>
    <input type='submit'/>
    </form>
  `)
};

Answer №1

Integrate view pass URL from Rails: include the following code snippet (make sure to update the path accordingly):

javascript_tag("window.UPDATE_URL = #{update_user_path(current_user)};")

then in JavaScript

  $.ajax({
    url: window.UPDATE_URL,

Answer №2

According to the details provided in the post, here are a couple of ways to achieve the desired outcome:

1) You can directly access the variable in the script tag:

var user_id = <% current_user.id %>

2) Another option is to attach the id passed from the controller to an element in the HTML body.

Then you can retrieve the value of the id from the element where it was set.

I hope this information proves helpful!

Answer №3

After some troubleshooting, I finally cracked the code by simply adding ${this.href} into the URL field.

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

Unable to unfollow using js code

JavaScript Fiddle In my current project, I am implementing follow and unfollow buttons. The follow functionality is working smoothly, but I'm facing an issue with the unfollow button. When I click on it, it doesn't switch back to follow. You can ...

Symfony2 AJAX form field updateIs Symfony2 form field update with

Here is a form I have: <form action="{{ path('book_create') }}" method="post" {{ form_enctype(form) }}> {{ form_start(form) }} {{ form_row(form.bookFoto) }} {{ form_row(form.bookTitle) }} {{ form_row(form.categories) }} < ...

Ensuring proper execution of the next callback function in an Express get request

I am currently running an express server on nodejs with a specific file structure that I need to convert into a list of links. Included below are my recursive functions for dealing with the file structure. Here are the file structure functions: function ...

Is it feasible to implement hot swapping in Node.js?

Can Node.JS support or mimic hot swapping code functionality? If so, what is the process? Hot swapping, also known as hot plugging, involves replacing or adding components without system shutdown. Erlang and Lisp have native support for hot swapping. ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >3 ...

Replacing a string in a textarea using Jquery

Trying to dynamically replace a string value in a textarea while typing into a textbox using jQuery. Utilizing the keypress event for this functionality. Any ideas on what could be causing issues with this example? <input type="text" id="textbox" /> ...

What is the best approach to transform an HTML textarea value into JSON format?

Client .. inserting some content into a form <textarea name="data"></textarea> After typing the following data into the textarea: {title: 'Hello one!', author: 'someone'} {title: 'Hello two!', author: 'mygf ...

Save the current active tab when refreshing the page

Struggling to find a way for the browser to remember the last active tab but haven't been successful. function ShowMyDiv(Obj){ var elements = document.getElementsByTagName('div'); for (var i = 0; i < elements.length; i++) if(element ...

Troubleshooting: Issues with PHP Ajax file upload functionality

Can anyone assist in troubleshooting this issue? I'm attempting to use AJAX to upload a file, but for some unknown reason, the code isn't functioning as expected. The uploaded file is not being copied to the designated location. function save() ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

Sending form data using Ajax

My concern is quite straightforward - I am using jquery and ajax to submit a form. When the button is clicked, the data gets sent to the database. The question is - if the user clicks the submit button twice, there will be two entries in the database. Ho ...

Struggling with aligning rows containing three divs each in Rails and bootstrap

Looking to display 3 article divs in each row on my website using bootstrap 3 grid system: <div class="container-fluid"> <h1>NEWS</h1> <div class="row"> <% @articles.each do |article| %> <div class="col- ...

The issue of React UseEffect not functioning properly in conjunction with firepad and firebase has been identified

When attempting to utilize the username fetched from Firebase to create a user in the FirepadUserList, the code resembles the following: import { useRef, useEffect, useState } from 'react'; import 'codemirror/lib/codemirror.css' impo ...

knockout, loop within a loop

Imagine I have a group of Humans who own Cats, and those Cats have Kittens class Person { String name; Cat[] cats; } class Cat { String name; Kitten[] kittens; } class Kitten { String name; } Now I want to display all my Kittens with ...

Is implementing an API necessary for handling this basic event in Express JS?

Lately, I've been encountering challenges with the backend, particularly when working with Express JS. I realize that part of the problem might be my own misunderstanding - assuming that Express JS is a framework generator for MVC or solely for authen ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Ways to restrict the generation of documents linked to the identical parent reference

Concept Explanation In the development of my VPN app, I am working on organizing orders and plans. Each order includes an array of associated plans. While filtering plans during population is possible, I aim to restrict the creation of plans per order to ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...