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.
Yours is a perfect use case of of rendering a partial through a ajax call.
So what you can do is:
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 )
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.
Related
Here is my predicament: I need to render json response received from controller method. I do this by calling clicking on navbar item "List Articles" which activate method ajaxIndex(). Then tat method makes request to route which in turn call controller method also called ajaxIndex(). That method then gater all articles and sends it as a response. After that, that response i can't control, it just renders raw json ...
Navbar item:
<a class="nav-link" href="/articles" onclick="ajaxIndex(this)"> List Articles </a>
Route:
Route::get('/articles', "ArticlesController#ajaxIndex");
Method in ArticlesController
public function ajaxIndex(Request $request)
{
$var1 = $request->var1;
$var2 = $request->var2;
$elem = $request->elem;
$currUser = auth()->user();
$currUri = Route::getFacadeRoot()->current()->uri();
$articles = Article::orderBy("created_at","desc")->paginate(5);
$html = view('articles.List Articles')->with(compact("articles", "var1", "var2", "elem", "currUser", "currUri"))->render();
//return $request;
return response()->json(["success"=> true, "html" => $html], 200);
//return response()->json(["success"=> $articles,"var1"=> $var1, "var2"=> $var2, "elem"=> $elem, "currUser" => $currUser, "currUri" => $currUri], 200);
}
and here my ajax method
function ajaxIndex(me,formId){
let var1 = "gg";
let var2 = "bruh";
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = "/articles";
if(formId){
let form = $("#"+formId).serialize();
console.log(form);
}
$.ajax({
type: "GET",
url: url,
headers:{
"X-CSRF-TOKEN": token
},
data: {/*
var1: var1,
var2: var2,
elem: {
id: me.id ? me.id : null,
class: me.className ? me.className : null,
value: me.value ? me.value : null,
innerHTML: me.innerHTML ? me.innerHTML : null,
}
*/},
success: (data) => {
console.log(data);
$('#maine').html(JSON.parse(data.html));
},
error: (data) => {
console.log(data);
}
});
}
How to render acquired data to particular view?
Now just renders json response alongside html.
My question is how to render response itself and where goes response from controller method. I tried console logging it when route is hit, but there is nothing in console. What is actual approach or what i need to change to achieve this?
Addendum: "For List Articles you will send ajax request to rest api where it returns array of objects(articles)". I assumed i needed to make ajax request, after being sent to appropriate blade, i should now display sent data? Am i getting wrong something? ...
Edit1:
Now when i go to any page in my app, for example:
http://articleapp.test/articles?page=2
it shows json response:
Edit2:
I also modified my ajax method to correctly display current page for article listing. Problem start when try to go to next page.
Here is the code:
function ajaxIndex(me,formId){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = "/articles";
if(formId){
let form = $("#"+formId).serialize();
console.log(form);
}
$.ajax({
type: "GET",
url: url,
headers:{
"X-CSRF-TOKEN": token
},
data: {},
success: (data) => {
console.log(data);
let html = "<div class='container'>";
let articleBody = "";
let pagination = "<ul class='pagination'><li class='page-item'><a class='page-link' href='#'>Previous</a></li>";
if(data.articles.data.length > 0){
for(let i=0;i<data.articles.current_page;i++){
let created_at = data.articles.data[i].created_at.replace(/-/g,"/").split(" ")[0];
html += "<div class='row' style='background-color: whitesmoke;'><div class='col-md-4 col-sm-4'><a href='/articles/"+data.articles.data[i].id+"'><img class='postCover postCoverIndex' src='/storage/images/"+data.articles.data[i].image+"'></a></div><div class='col-md-8 col-sm-8'><br>";
if(data.articles.data[i].body.length > 400){
articleBody = data.articles.data[i].body.substring(0, 400);
html += "<p>"+articleBody+"<a href='/articles/"+data.articles.data[i].id+"'>...Read more</a></p>";
}
else{
html += "<p>"+data.articles.data[i].body+"</p>";
}
html += "<small class='timestamp'>Written on "+created_at+" by "+data.articles.data[i].user.name+"</small></div></div><hr class='hrStyle'></hr>";
history.pushState(null, null, "/articles?page="+(i+1));
}
for(let i=0;i<data.articles.total;i++){
//console.log(data.articles.data[i].id);
pagination += "<li class='page-item'><a class='page-link' href='/articles?page="+(i+1)+"'>"+(i+1)+"</a></li>";
}
pagination += "<li class='page-item'><a class='page-link' href='#'>Next</a></li></ul>";
}
html+="<div class='d-flex' style='margin: 10px 0px;padding-top: 20px;'><div class='mx-auto' style='line-height: 10px;'>"+pagination+"</div></div></div>";
$('#maine').html(html);
//?page=2
},
error: (data) => {
console.log(data);
}
});
}
When i go to next page, it shows json response as i previously stated. Look in the image above. It won't render ...
In this case ajax response should contain only the real content you want to get with the assynchronous request (html tags inside body). Your #maine element should be a div or another structure capable of having html child tags.
Ps.: If you want to render the ajax response like another page by changing header tags and maybe even the http content type then the response should be load inside an iframe tag.
**Edit: ** In pratice, delete the previous content before body tag in the view returned by ajax. And #maine must be a to contain the ajax response.
I'm looking at the Slack API for use in teaching API Consumption in Ruby. Does the Slack API require all the parameters as part of the query string or can it take post-Params as well.
Messages like this work:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}" + "&text=#{msg}&channel=#{channel}"
data = HTTParty.post(url)
end
However this does not:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}"
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}"
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
end
I think the cleanest answer is just this:
url = 'https://someslackwebhookurl/adfdsf/sdfsfsd'
msg = 'We are fumanchu'
HTTParty.post(url, body: {"text":"#{msg}"}.to_json)
I have managed to answer the question with:
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}",
"username" => bot_name,
"icon_url" => icon_url,
"as_user" => "false"
},
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' })
It won't work with JSON content oddly enough.
I am currently requisition an html partial to be inserted into a modal
$('#user-addTool').on('click', function(e) {
$('#userModal div.modal-content').html('');
var ajaxUrl = "http://" + window.location.host + "/users/new";
e.preventDefault();
e.stopPropagation();
$.get(ajaxUrl, function(data){
$('#userModal div.modal-content').html(data);
initGroupSelector();
initRoleSelector();
$('#role-selector').multiselect('disable');
}, "html");
$('#userModal').modal('show');
});
served by a rails app :
# GET /users/new
# GET /users/new.json
def new
#user = User.new
#user.profile = Profile.new
authorize #user
render partial: 'users/form', layout: false
end
I wonder if I can return both, the partial form html AND a son object ( groups and roles to be used in the client js script ?
thanks for feedback
UPDATE 1 --
Can I send a JSON response this way ?
format.json {
#response = {
"html": { "form": <%= (render partial: 'users/form').to_json.html_safe %> },
"data": { "groups": <%= #groups %> , "roles": <%= #roles %> }
}
render(json: #response, status: :success )
}
In which #group is an Array of Arrays and #roles a Hash of Hashes ?
thanks for advices
I have a datepicker function that was working pefectly well until I internationalized my application. But now, it's not working anymore. Here is my Ajax function :
$datepicker.change(function(){
currentDate = $datepicker.datepicker( "getDate" );
dateString = $.datepicker.formatDate("yy-mm-dd", currentDate);
console.log("My dateString is: "+dateString);
Here my console is showing the right date
$.ajax({
type: "POST",
url: "movements/getTO/",
data: {"date":dateString},
}).done(function(data) {
$("#resultTO").html(data[0])
$("#resultQty").html(data[1])
});
});
with this controller function :
def getTO
selected_date = Date.parse(params[:date])
new_html_to_return1 = Movement.where(:movement_date =>selected_date, :user => current_user.email).sum("turnover")
new_html_to_return2 = Movement.where(:movement_date =>selected_date, :user => current_user.email).sum("quantity")
#table = [new_html_to_return1, new_html_to_return2]
render :json => #table
end
My routes.rb :
post "movements/getTO"
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
resources :movements
(...)
end
match '*path', to: redirect("/#{I18n.default_locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
match '', to: redirect("/#{I18n.default_locale}")
At this point, my datepicker was having a route trouble. So I added in routes.rb
match 'movements/getTO', to: redirect("movements/getTO")
But that's not right because now I have as output : < and !. Incredible for sums isn't it ???
I have a view with one argument, and a set of exposed filters. When the user filters the view, the form is submitted using Ajax, and the filters are appended to the url using location.hash.
My goal is to filter the view upon initial page load, if the filters are present in the location.hash.
Currently, I'm loading the view through an Ajax callback, which works perfectly fine. But the big problem is that Ajax for the view doesn't work.
This is the callback that loads the View.
// Load the view object.
$view = views_get_view('taxonomy_term');
$view->set_display('page');
$view->set_use_ajax(TRUE);
// Pass the current tid as the argument.
$view->set_arguments(array($tid));
// Set the current page.
$view->set_current_page($page);
// Set the exposed filters.
$view->get_exposed_input();
// Execute.
return $view->execute_display();
When I navigate directly to that callback, everything works. But not when I load it through Ajax.
Any ideas?
Update:
It seems that Drupal.behaviors.ViewsAjaxView() doesn't execute for some reason. If I execute it manually, everything works.
Ok, so I've found the answer.
Instead of loading the View from my own callback, I'm now loading the View from the regular ajax callback.
On my page, I create the view object, and add the configuration to Drupal.settings.
$view = views_get_view('taxonomy_term');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
'views' => array(
'ajax_path' => url('views/ajax'),
'ajaxViews' => array(
array(
'view_name' => $view->name,
'view_display_id' => $view->current_display,
'view_args' => check_plain(implode('/', $view->args)),
'view_path' => check_plain($_GET['q']),
'view_base_path' => $view->get_path(),
'view_dom_id' => 1,
'pager_element' => $view->pager['element'],
),
),
),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');
Then I load my js, which adds the current filter from the location.hash to the settings. And finally, loads the View.
var data = {};
// Add view settings to the data.
for (var key in Drupal.settings.views.ajaxViews[0]) {
data[key] = Drupal.settings.views.ajaxViews[0][key];
}
// Get the params from the hash.
if (location.hash) {
var q = decodeURIComponent(location.hash.substr(1));
var o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}};
$.each(q.match(/^\??(.*)$/)[1].split('&'), function(i,p) {
p = p.split('=');
p[1] = o.f(p[1]);
data[p[0]] = data[p[0]]?((data[p[0]] instanceof Array)?(data[p[0]].push(p[1]),data[p[0]]):[data[p[0]],p[1]]):p[1];
});
}
$.ajax({
url: Drupal.settings.views.ajax_path,
type: 'GET',
data: data,
success: function(response) {
var viewDiv = '.view-dom-id-' + data.view_dom_id;
$('#content > div.limiter').html(response.display);
// Call all callbacks.
if (response.__callbacks) {
$.each(response.__callbacks, function(i, callback) {
eval(callback)(viewDiv, response);
});
}
},
error: function(xhr) {
$('#content > div.limiter').html('<p id="artist-load-error">Error text.</p>');
$('#block-request-0').hide();
},
dataType: 'json'
});
This way, the view loads through the regular flow, and everything works as expected =)