简体   繁体   中英

Rails - HTTParty request through AJAX

I am new to both Rails and AJAX. I want to consume an API which is hosted on a different website. I ran into problems with cross origin HTTP request. So I tried doing this by using HTTParty.

In the code below, I am setting the text of $(".result") as JSON.parse(HTTParty()) request, so that it can query the website and give me the result.

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>

Now comes the weird problem. The code above does send the GET request to example.com (placeholder), but gets a response saying that it is not a valid query.

However, if I pass the str1 as follows -

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

I get the expected response. If the $(".ajax-control") text field is "xyz", I get a response saying not a valid query.

Does string concatenation in javascript introduces new characters because of which it is throwing an error?

That javascript (which in turn has ruby code via erb) is not going to execute after its been rendered the first time by Rails.

That is, its not going to be invoked each time that keypress callback is called, which means that when Rails is rendering that Javascript it obviously has no knowledge of the client-side DOM so the URL is affectively:

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

And the remote server has an empty param which it doesnt like...

If you really need to invoke that API for every keypress you have two options:

  1. Get it to work via Ajax using CORS
  2. Invoke an endpoint in your Rails app, which in turn uses Ruby-side HTTParty to invoke the API and relay the response back to the client.

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