简体   繁体   中英

Rails : get json value in hidden_field form (giphy api)

I am using the Giphy search API to let my users search for gifs and let them add gif.

Here is simplified part of my code to make it works :

_Form.html.erb

<%= form_for Task.new do |f| %>
<%= f.hidden_field :gif, id: "GifUrl", value: "" %>
<input type="text" name="search" placeholder="Search gif">
<!-- This part render the gif search result -->
<div id="score"></div>
<% end %>

Part of my script where I fetch the details of the gif from giphy

  this.displayResult = function(url) {
    const target = document.getElementById('score');
    const img = document.createElement('img');
    img.src = url;

    target.appendChild(img);
  }

What I wanted to do is to scrape the html src value of the gif link returned and pass it in my form through an hidden_field, but it returns : [object Object] as a value, instead of the proper gif link.

 => #<Task id: 285, description: "", user_id: 37, gif: "[object Object]">

Should I use an html parser like nokogiri or am I doing something wrong ? How can achieve this ?

Thanks !

It looks like when using the giphy-api you get a json response . You should look into just using the URL of the image size you would like to store. IE

$("#GifUrl").val(
  giphy_response['data'][SEARCH_RESULT_TO_USE][images][IMAGE_SIZE_TO_USE]['url']
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM