ruby, sinatra, Plivo API: render API call as HTML

439 Views Asked by At

I am making an API call to Plivo to list available telephone numbers.

I can access the returned response and print the desired elements in my terminal BUT I do not know how to render them as HTML on my web page. This is my problem.

In the terminal, the response to a successful call is:

  {"api_id"=>"23f1f0f0-0808-11e3-a442-22000ac6194a",
 "meta"=>
  {"limit"=>1, "next"=>nil, "offset"=>0, "previous"=>nil, "total_count"=>1},
 "objects"=>
  [{"group_id"=>"23928520636825",
    "number_type"=>"local",
    "prefix"=>"646",
    "region"=>"New York, UNITED STATES",
    "rental_rate"=>"0.80000",
    "resource_uri"=>
     "/v1/Account/MAZDQ1ZJIYMDZKMMZKYM/AvailableNumberGroup/23928520636825/",
    "setup_rate"=>"0.00000",
    "sms_enabled"=>true,
    "sms_rate"=>"0.00800",
    "stock"=>50,
    "voice_enabled"=>true,
    "voice_rate"=>"0.00900"}]}
"0.00900"
New York, UNITED STATES
646

The Ajax script which generates the response is:

$(".localsearch").click(function() {
    var country_iso = $("#local").val();
    var region = $("#region").val();
    var prefix = $("#prefix").val();
    $.ajax({
    type: "GET",
    url: "/local/data",
    data: { 'country_iso' : country_iso,  'region' : region,  'prefix' : prefix },
    success: function(data) { 
    alert(data)
            },
     });
 });

The alert doesn't help and just shows the entire page.

The ruby code is:

get '/local/data' do
      country_iso =  params[:country_iso]
      region = params[:region]
      prefix = params[:prefix]
      p = RestAPI.new(AUTH_ID, AUTH_TOKEN)
      params = {'country_iso' => country_iso, 'region' => region, 'prefix' => prefix, 'limit' => '1'}
      response = p.get_number_group(params)
      obj = response.last
      pp response.last 
      @region = obj["objects"][0]["region"]
      puts @region
      @prefix = obj["objects"][0]["prefix"]
      puts @prefix
     erb :search
end

So, sorry it's long and to summarize, how do I extract elements from the API response and print them as HTML? Many thanks in advance.

In the view I have tried:

<%= @region %> and <%= obj['region'] %> and <%= obj['objects][0]['region'] %>and none of them work.

1

There are 1 best solutions below

5
On

Yours is a perfect use case of of rendering a partial through a ajax call. So what you can do is:

  1. Make your Sinatra action return html using rails like render partial functionality like this http://steve.dynedge.co.uk/2010/04/14/render-rails-style-partials-in-sinatra/ (to get rails like partial functionality in sinatra you can use this gem also https://rubygems.org/gems/sinatra-partial )

  2. Now since now your sinatra action returns a valid html, in your ajax success function you can just write:

    $(".localsearch").click(function() {
    var country_iso = $("#local").val();
    var region = $("#region").val();
    var prefix = $("#prefix").val();
    $.ajax({
       type: "GET",
       url: "/local/data",
       data: { 'country_iso' : country_iso,  'region' : region,  'prefix' : prefix },
       success: function(data) { 
          $('unique_identifier_of_your_partial_on_the_html_dom').html(response)
       }
    });
    

    });

another example of rendering partial in sinatra: Ruby w/ Sinatra: Could I have an example of a jQuery AJAX request?

extract out the html that you want to populate with the response from this ajax call into a a separate erb file lets say , _my_response_partial.html.erb now suppose this is your search.html.erb file.

#something somrthing
<%= erb(:my_response_partial, locals => {:region => @region, :prefix => @prefix},:layout => false) %> #pass whatever data you want to pass to a partial using locales
# something something

and in your get action replace the last line with:

erb(:my_response_partial, locals => {:region => @region, :prefix => @prefix},:layout => false)

By this way your action will just return the html required to populate that partial.