Utilizing AJAX to send HTTParty requests in Rails

I am a newcomer to both Rails and AJAX. My goal is to access an API hosted on a different website, but I encountered issues with cross-origin HTTP requests. To overcome this obstacle, I decided to utilize HTTParty.

Within the code snippet below, I am instructing $(".result") to display the parsed JSON result of my HTTParty request. This setup should allow me to query the external website and retrieve the desired outcome.

Rails code:

<%= form_for(@profile) do |f| %>
  <%= f.label :content %>
  <%= f.text_field :content, class: 'ajax-control' %>
  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>

<p class="result"></p>

Javascript code:

<script>
  $(document).ready(function(){

    $('.ajax-control').on('keyup',function(){
       var charCount = $(this).val().length;
       if(charCount===3){
        var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param='+$(this).val()+'"))%>'
        $(".result").text(str1);
       }
    });
  });
</script>

However, there's a peculiar issue at hand. The current code successfully sends a GET request to example.com (placeholder), but receives a response indicating that the query is invalid.

Interestingly enough, when I manually input the following syntax -

var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param=xyz"))%>'
 $(".result").text(str1);

I receive the expected response. If the text within $(".ajax-control") is set as "xyz", the response indicates that it's not a valid query.

This begs the question: could string concatenation in javascript be introducing additional characters that are causing this error?

Answer №1

The javascript code, which contains ruby code via erb, will not run again after it has been initially rendered by Rails.

Essentially, the code will not be triggered every time the keypress callback is called. This means that when Rails renders the Javascript, it does not have access to the client-side DOM, so the URL effectively looks like this:

JSON.parse(HTTParty.get("http://example.com/api.php?param="))

Due to an empty parameter on the remote server, this setup poses issues...

If you absolutely need to call that API with every keypress, you have two choices:

  1. Make it work with Ajax utilizing CORS
  2. Create a new endpoint within your Rails application, which then uses Ruby-side HTTParty to call the API and send back the response to the client.

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

From PHP to Ajax: Transforming Web Functionality

As a newcomer to the world of coding, I recently achieved a milestone by successfully creating a PHP code snippet. By utilizing TwitchTV's API, I was able to display the game currently being played on TwitchTV. The code is up and running smoothly. $i ...

What is the best way to retrieve data as a List from a JSON file using Retrofit?

When trying to fetch data as a List instead of a single entity, an error occurs: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ To see the JSON link associated with this issue, click here: The method used to retrieve JSON Data in Main ...

Exploring the functionality of test code within an rxjs subscription by utilizing the powerful technique of jasmine

My goal is to test the code within an observable subscription: function bar(someStream$: Observable<number>) { someStream$.pipe( map((x) => x + 3), ).subscribe((result) => { SomeService.someMethod(result) }) } I want to ensure t ...

The pattern() and onkeyup() functions are unable to function simultaneously

When trying to display a certain password pattern using regex while typing in the fields, I encountered a problem. The onkeyup() function works for checking if both passwords match, but it causes the pattern info box not to appear anymore. I'm curiou ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

"Clicking on the jQuery carousel dots results in always navigating back to the first item

Creating a carousel using basic jquery, utilizing the .css() rule to toggle opacity between slides. The goal is to have each dot trigger the display of its corresponding slide while hiding the others. Currently trying: $('.dot').click(function( ...

The parameter type 'NextHandleFunction' does not match the expected type 'PathParams' in the argument

After successfully setting up TypeScript with a basic Express server, I've encountered an issue. import bodyParser from 'body-parser'; import express, { Express } from 'express'; const app: Express = express(); app.use(bodyParser ...

Bootstrap form toggle switch component for ReactJS

I'm having trouble figuring out why the default value for my react-bootstrap switch won't set to false (off). It seems like the only way it changes is when I trigger the onChange event handler. Am I overlooking something? Below is the section of ...

Is it possible to have Vue.js code within a v-for loop in such a way that it executes every time the v-for loop runs?

<div class="questions" v-for="(q,index) in questions " :key="index" {{this.idx+=1}} > <h3 > {{q.content}}</h3> <h3> A) {{q.a}} </h3> <h3> B) {q.b}} </h3> ...

Correct the JSON format which contains key-value pairs

After creating the following JSON data, I realized it wasn't formatted correctly. The issue is with the inverted quotes in the key message and in null. NSString *chID=@"101"; NSString *reqId=@"REQID"; NSString *enTypeId=@"100"; NSStri ...

Is it possible to verify if a function is invoked using Jest, Typescript, and ts-jest in action?

Currently, I'm testing the functionality of this code snippet: src/helpers/CommentHelper.ts: export default class CommentHelper { gitApiObject: GitApi.IGitApi ; constructor(gitApiObject: GitApi.IGitApi) { this.gitApiObject = gi ...

Exploring Twitch API and React to visualize and display comments on a map

I am encountering an issue with mapping comments/results from a Twitch API. I am receiving a TypeError when attempting to map, and the API results are limited to 60 records with no apparent way to extend the mapping beyond that. This is the Component resp ...

`On mobile devices, the Bootstrap button no longer displays focus changes once clicked.`

When clicking a primary bootstrap button, it changes its background color to blue on mobile devices. https://i.sstatic.net/VNPDP.jpg For example, the first button appears normal and the second one turns blue after clicking. However, this background effec ...

Deactivating form elements using jQuery

I am attempting to utilize jQuery in order to disable a form element once a checkbox is clicked, but for some reason it's not working properly. Can someone help me identify the issue? $('name="globallyAddTime"').click(function() { if ($ ...

Alter the views of a bootstrap date picker in real-time

Is there a way to dynamically change the date picker's view based on different button selections? For example, I have buttons for month, year, and day. Here is what I am trying to achieve: When the month button is selected: I want the date picker ...

Swap out .h and .m files within an iOS project's bundle directory in real-time

I am currently using the calculation.h and calculation.m files for some calculations in my project. These calculations may need to be modified while the application is live on the store. Therefore, I can only make changes to these calculations and update t ...

Why is there a presence of quotation marks in the value stored in my local storage?

I have been attempting to extract data from a MySQL database using the following code: app.get("/api/getStudentsFromClass", async(req,res) => { const currentClassClicked = req.query.currentClassClicked connection.query( " ...

Updating MySQL Database in Laravel 5.2 with JSON Data retrieved from MongoDB

Is there a way to update a MySQL Database table using data retrieved from MongoDB? I currently have a function that fetches data from MongoDB $recordid = '9depnuDz1XHl'; $mongodata = MongoDataPull::find($recordid); Upon executing the code: r ...

Unlocking the Secrets of Accessing Variables from Different Functions in JavaScript

Is there a way to access a variable from one function in another function without defining it outside of the functions? Here's an example code snippet for reference: http://jsfiddle.net/VC6Wq/1/ function one(){ var zero= 500; } function two(){ alert ...