Is there a way for me to retrieve ruby/rails app variables from an external JS file?

I am currently developing an internal application to monitor the performance of paid search advertising.

Imagine I have several paid search campaigns directing traffic to different websites (referred to as "target sites"). When a user clicks on a paid ad and reaches the target site, a cookie is created using JavaScript. If the cookie is detected (indicating they came from AdWords), I replace the default phone number on the page with a tracking number.

To achieve this, I include a JS file from my Rails app on the target site like this:

<script src="http://www.myapp.com/assets/application.js" type="text/javascript"></script>

Key parts of the JS script:

if(window.location.href.indexOf("gclid") > -1) {
       document.cookie = "ppc=adwords; path=/";
    }


function getCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return unescape(c.substring(nameEQ.length, c.length));
        }
    }

    return "";
}


var value = getCookie('ppc'); 
if (value != '') { 
  // User has the cookie, indicating they came from gclid
    alert("this user has the ppc cookie!");

    var testswap = function(){
        var swap = document.getElementById("test").textContent;
        document.getElementById("test").textContent = "New Number Insert";
    }
    document.addEventListener("DOMContentLoaded", testswap);

} else { 

    alert("user doesn't have cookie");
  // User does not have the cookie, meaning they came from elsewhere
}

I keep each account's paid search number in the app's database. How can I best access it to replace the number in this line from the above script

document.getElementById("test").textContent = "New Number Insert from app's database";

I initially thought using the gon gem would solve this, but I realized it cannot access the controller-set variables on the target site (I understand now that this might not be feasible, even after referencing the JS file on the target site). Should I consider using AJAX?

Disclaimer: I am relatively new to programming, so I apologize if this explanation could have been clearer. I also acknowledge that the code may not be optimal, which could complicate the resolution.

Any assistance would be highly appreciated!

Answer №1

If you create an additional controller that searches for the user's number using cookie data (or any other related value), you can retrieve it using ajax.

Please keep in mind that this code has not been tested.

Here is an example of how you can set up the controller and configure your routes:

 class UsersController < ApplicationController
   def fetchUserNumber
     @cookieValue = params[:cookie]
     @user = User.where(cookie: @cookieValue).first
     render json: @user.to_json
   end 
 end

Then, in your application.js:

  $.get("<your controller route>", {cookie: value}, function(data){
      var updateNumber = function(){
          var currentNumber = document.getElementById("test").textContent;
          document.getElementById("test").textContent = data.number;
      }
  });

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 fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

Having trouble with JQuery's $.post function not functioning on your web server?

I'm encountering an issue with my script that uses Ajax to send a request to my PHP file for updating a txt file. Interestingly, the script works perfectly fine on my localhost but fails to work on the webserver. Testing HTML code: <!DOCTYPE html ...

Send user input to a Controller method using Ajax

I am working on a MVC3 page that includes a link (Ajax.ActionLink). When the user clicks this link, it triggers a controller action and the result is displayed in a div, replacing the existing content. Here is the code snippet: @Ajax.ImageActionLink("/Im ...

Laravel: Solving the 405 Error When Using Ajax with POST Method

Trying to extract the value from an ajax response and use it to populate a select box. I've managed to fetch the field value and send it to another page using ajax. However, when checking the console, I see the message POST http://localhost/pject_name ...

Innovative Inter-Browser Link with a Distinct Shape

I am currently developing a web application that enables users to input content and then send it out to their phones. Everything is working smoothly, but I am facing an issue with the logo design. The logo in question is displayed as follows: On the left ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

Transforming an ASP.NET webpage into a PDF format using Ajax Tab Container

I'm currently working on a website that involves a lot of data import and export. The user's data is being displayed in an ajax tab container, but I've run into an issue when trying to export this data to PDF: Script control 'TabPanel1 ...

What could be causing my chessboard to not wrap around properly with flexbox?

I have been working on creating an 8x8 chessboard by following this example: https://codepen.io/sammyslamma/pen/gJeOwY .flex-container { display: flex; flex-flow: row; flex-wrap: wrap; ...

Distinguishing Between server.listen() and app.listen() in Google Apple Engine

I am currently working on a NodeJS + Express application. While running it locally, I have the following code: const port = 3001; server.listen(port, () => { console.log(`App listening on port ${port}`); }); However, when deploying to GAE, I switch ...

Filtering a string that contains commas using another string that also contains commas

I need help with removing elements from one comma-separated string based on another. String 1: 6,2 String 2: 1,2,4,5,6,7,9,12,13 Is there a function or method that can accomplish this task for me? ...

Best practices for locating unique symbols within a string and organizing them into an array using JavaScript

Here is an example string: "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>" The characters A, B, C, and so on are variables, and their count is not fixed. Can you determine how many ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

Are there any similar tools to Graphstream in Java that can be used with HTML5 using canvas and JavaScript?

GraphStream is a revolutionary graph library created in Java that offers Java developers a simple way to visually represent dynamic graphs either in memory, on screen, or in files. Check out this demo video. With GraphStream, you can effectively handle th ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

Issue with React.js button functionality not functioning as expected

import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { items: [] } } addItem(e) { var itemArray = this.state.items; ...

You need to click the React onClick button twice in order to successfully trigger the API

I want to configure React so that when clicked, it will run process.env.REACT_APP_LOGOUT and remove the item set in local storage. Currently, it requires two clicks to execute. The first click redirects to the index page, and then a second click is needed ...

Display XML information when a row in the table is selected

I am working with an XML data sheet and utilizing ajax to extract information from it in order to generate specific tabs and construct a table of data. However, I am encountering a challenge when attempting to display details in adjacent divs once a row of ...