Guide on sending a POST request and fetching JSON data in Ruby on Rails

Despite going through numerous questions, I am still perplexed.

My current project involves creating a Rails application that interacts with the Healthgraph API (link here ).

I am required to send a POST request using Rails based on a received parameter and then handle the JSON response. I attempted to use various gems like oauth2 and runkeeper, but they failed due to specific dependencies. My challenge lies in properly executing a POST request via Rails and managing the returned information.

While I do receive the code back in my controller, acquiring an access token remains elusive.

def rktest

respond_to

if params[:code]
  require 'oauth2'

  @code=params[:code]

  @cc_id=client_id
  @client_s=client_secret

else

  @code="None"

end

I've also experimented with Javascript for this task, which raises concerns about exposing sensitive client secrets. Additionally, I've been unsuccessful in receiving data back through this method as well.

<script type="text/javascript" src="javascripts/jquery-1.7.1.min.js"></script>

<script type="text/javascript">

function get_access_token(code,ccid,cc_s){

$.ajaxSetup({
'beforeSend': function(xhr){
xhr.setRequestHeader("Accept", "text/javascript")
}
});

var sent = { 'grant_type': 'authorization_code',
'code': code,
'client_id': ccid,
'client_secret': cc_s,
'redirect_uri': 'http://myurl.com/rktest'
};

document.write("<p>" + sent + "</p>");

$.ajax({
url: 'https://runkeeper.com/apps/token',
data: sent,
type: 'POST',
dataType: 'json',
success: function(data, status, xhr){
if (status === 'error' || !xhr.responseText){
handleError();
}else{

document.write("<p>" + data + "</p>");
document.write("<p>" + status + "</p>");
document.write("<p>" + xhr + "</p>");

}
}
});

}

<%= 'get_access_token(\''+@code+'\',\''+@cc_id+'\',\''+@cc_s+'\');' %>                

Here is the current content of my routes file:

match '/rktest', :to => 'main#rktest', :via => [:get, :post]

Unfortunately, even after implementing this configuration, the desired outcome is not achieved.

RestClient.post 'https://runkeeper.com/apps/token', {:params => {
    :grant_type => 'authorization_code',
    :code => @code,
    :client_id => '8e9b36478b764ac38ef1bdabc6d14d60',
    :client_secret => something,
:redirect_uri => "http%3A%2F%2Fopenhealthdesigns.com%2Frktest"}}

Answer №1

Check out this helpful resource:

Answer №2

In my controller file, I've implemented respond_to :json at the beginning and used respond_with @notes in the specific method for returning JSON data, which has been functioning smoothly.

The application utilizes Ajax to retrieve data for a search feature, and I don't believe that the way the data is fetched should have any impact on the outcome.

Adding a bit more code for better understanding:

class NotesController < ApplicationController
  require 'coderay'
  respond_to :json                                                                                                                                                                                                         


 def search
  @notes = Note.fulltext_search(params[:title])
  @notes.each do |n|
    n.content = CodeRay.scan(n.content, :ruby).div(:css => :class)
  end
  respond_with @notes
end

API documentation - depending on the calling method, using .json could also work with a respond_to block in place.

respond_with

respond_to

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

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

Converting an HTML div to a string for export

In the process of developing my application, I am utilizing an angular widget to construct a dynamic dashboard. Here is the snippet of HTML code along with the associated JavaScript that enables this functionality: <div class="page" gridster="gridsterO ...

Exploring: Accessing the Tags Attribute

For a project, I am integrating wicket and jQuery together. In my HTML, I have: <a wicket:id="link" testAttr="test"></a> With jQuery, I am updating this attribute when other components on the page are clicked. My question is: how can I retri ...

Is it possible to delete an item from both the input button and the list?

Asking for help with an issue -> https://stackblitz.com/edit/dropdown-fill-empty-uecsjw?file=src%2Fapp%2Fapp.component.ts Current problem description. The issue I am facing is that after selecting items from a drop-down menu and then deleting them usi ...

Can you explain the significance of the file:workspaces in the package dependencies?

Attempting to utilize npm 7 workspaces feature "workspaces": { "packages": [ "packages/apps/*", "packages/components", ], Upon installation, my package.json includes: "dependencies": ...

One way to specify a callback is by embedding a function within another function. This can be accomplished in JavaScript ES

A.file function Carousel(){ ~~~~~~ code ~~~~~~ this.add = function(data){ do_something() self.addCallback.call(this, arguments) }; this.remove = function(data){ do_something() this.removeCallback.call(this, arguments) }; ...

Best method for combining objects in a tidy manner

I have multiple objects with similar structures, where some have null values for certain fields and one object (obj2) has values for those fields that are null in the others. I want to merge them and consider the values from obj2: var obj2 = { options ...

I am facing difficulty creating a dropdown menu with nested options that only appear when the user hovers over the main selection

Here are the parent options I have and the code I have attempted to build. I would like to include sub-options such as phones, radios, speakers under the electronics parent option and many more. <select id="category" name="category" class="dropDown"& ...

ng-repeat unable to function within a textarea

Could you help me troubleshoot why the ng-repeat is not functioning properly within a textarea? Oddly enough, it works fine when moved outside of the textarea. <textarea> <style ng-repeat="entry in bgTakeoverSettings.breakPoints"> ...

The onClick event within the pageinit function only triggers once the page has been refreshed

Despite my attempts to search for a solution in existing duplicate questions, I have been unable to find one that fits my specific problem. Here's the issue at hand: I have a banner that appears on every page of my project. Within the banner, there a ...

Tips on triggering ng-click event before the page finishes loading

Is there a way to have the "edit" button appear in a "clicked" state when the page first loads? <div class="buttons" ng-show="!rowform.$visible" style="width: 20%"> <button class="btn btn-primary" ng-click="rowform.$show()">edit</butt ...

Unlocking the power of NextAuth by incorporating wild card or custom domains into the signin logic

My NextJS application is a multi-tenant SaaS application where each customer can choose to use a subdomain on our site or map their custom domain via CNAME. This setup allows customers to enable their employees to log in on either the subdomain site or cu ...

The IMG onclick event for LinkModalDialog does not function properly on Mozilla browsers

I am currently utilizing the following function: function OpenLinkModal(obj){ var arr=showModalDialog("../../files/list_simple.asp","","dialogHeight: 600px; dialogWidth: 450px; edge: Raised; center: Yes; resizable: Yes; status: Yes; scroll: Yes; help ...

Retrieve every video on React.js channel from YouTube

Currently, I am working on integrating react-youtube into my React App with the goal of accessing all videos from a specific YouTube channel. The challenge I am facing is that I need to display these videos as thumbnails, exactly how they are listed in the ...

Adding an image to a jQuery class name on the fly

I am attempting to add an image before a div by using its className with jQuery. function insertImage(obj) { var dynamicClass = $(obj).prop("className"); After retrieving the classname, I now encapsulate it in single quotes and add a dot to access t ...

React: Component failing to re-render despite update in array state (distinct from other cases)

Can someone help me troubleshoot an issue on my page where the images are not displaying after being downloaded from the server? The page doesn't re-render even after updating the state with a fresh array as suggested. It's strange because the co ...

Display or conceal the nearest element that was clicked

http://jsfiddle.net/KevinOrin/xycCx/1/ jQuery('.happening-main-text .readmore').click(function() { jQuery('.divmore').toggle('slow'); return false; }); ...

Dealing with memory leaks in three.js can be a common issue, especially when utilizing the

In my three.js project, I am constructing a Geometry and filling it with vertices to create a 2D terrain. Once the terrain is generated, I am adding all the Vector3 and Face3 elements to the geometry, and then adjusting each vertex and face on every frame ...

Executing Auth0 API calls after logging in with Next.JS: A step-by-step guide

In my Next.JS app, I successfully set up auth0 login by following the documentation: // pages/api/auth/[...auth0].js import { handleAuth } from '@auth0/nextjs-auth0'; export default handleAuth(); // pages/index.js import { useUser } from ' ...

Sending an Ajax POST request from a Node.js server

I am running a Node.js server with Socket.IO that communicates with a Python server using Django. I am looking to make a POST request from the Node.js server to the Django server on a specific method without utilizing any jQuery functions due to their depe ...