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?