render geojson w/ respond_to rails & mapbox/leaflet - ruby-on-rails

So I am currently trying to request some geojson data from my rails controller. I am using the loadURL method provided to me through mapbox/leaflet to make the ajax call to my controller.
$(document).on("ready", function() {
L.mapbox.accessToken = 'token is here';
var userMap = L.mapbox.map('user-map', 'mapbox.run-bike-hike')
.addControl(L.mapbox.geocoderControl('mapbox.places'))
.setView([37.7833, -122.4167], 12);
var featureLayer = L.mapbox.featureLayer().loadURL('http://localhost:3000/users/1/trails.geoJson').addTo(userMap)
console.log(featureLayer);
// getTrailPoints(userMap);
featureLayer.on('ready', function(){
userMap.fitBounds(featureLayer.getBounds());
});
});
The above code is able to hit my controller and my controller is able to retrieve the correct data. Here is what I have in my controller:
def index
user = User.find_by(id: params[:user_id])
#trails = user.trails
#geojson = Array.new
build_geojson(#trails, #geojson)
p "*" * 50
p #geojson
respond_to do |format|
format.html
format.geojson { render geojson: #geojson }
end
end
The build_geojson method works fine, you will have to trust that. However, what is not working is the format.geojson and rendering it as geojson. I'm pretty sure I need to create a Mime but I am unsure how to do so or in what way I should go about doing it with geojson. Any help would be greatly appreciated. I will also answer any questions.
I do currently have it formatted in just json because geojson is just json. However with mapbox when I do that, I get the following error:
http://a.tiles.mapbox.com/v4/marker/pin-l-tree+00607d.png?access_token=pk.e…hIjoiNDQ5Y2JiODdiZDZmODM0OWI0NmRiNDI5OGQzZWE4ZWIifQ.rVJW4H9TC1cknmRYoZE78w Failed to load resource: the server responded with a status of 400 (Bad Request)
The error basically results in the image not being loaded.

There is no tree icon in the currently-supported Mapbox icons. Use park instead, which is also a picture of a tree.

Related

Responding to AJAX Rails request with .js.erb and Rails instance variable

I am struggling w/ JS AJAX requests in Rails. There is an official guide here, but I am having slight difficulties matching it with ES6 JS. I am having troubles passing things back to my frontend after making my requests.
I have a JS window.onload call made, because I am trying to find the user’s screen size (among other things) and pass it back to Rails:
let xhttp = new XMLHttpRequest();
const url = "/users";
xhttp.open("POST", url);
// Some other things added to it...
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
console.log(this.responseText);
}
};
xhttp.send(JSON.stringify({user_info: userInfo}));
It is posting to /users some information about the session. This is going through fine. Note the console.log that keeps track of the response, we will get to this later.
In my Rails controller:
def create
user_info = params[:user_info].permit!
user_info = user_info.to_s
#fingerprint_user = User.find_or_create_by(fingerprint: user_info)
respond_to do |format|
# NOTE: I have tried a few things here
# format.html { redirect_to #fingerprint_user, notice: "Successfully identified user by fingerprint." }
# format.js
format.json { render json: #fingerprint_user, status: :created, head: :ok }
end
end
The JSON sender is working correctly. The console.log in the JS above correctly console.logs the received JSON. The request responds with 201, and the #fingerprint_user instance variable in JSON form.
My problem is with returning ERB JS with the instance variable. As shown in the guide, I have tried adding format.js. Then, the request returns a 200, and the contents of my views/users/create.js.erb file:
console.log("hello");
However, it is not actually logging to console.
Lastly, I tried with all format fields (js, html, and json). Here is my show.html.erb:
<p>Got user: <%= #fingerprint_user.to_s %> </p>
Here is a better views/users/create.js.erb file, where fingerprint is a div in my index.html.erb:
console.log("hello");
$("<%= escape_javascript(render #fingerprint_user) %>").appendTo("#fingerprint");
Once again, the response is 200, and the appropriate html, but this is not rendered on the page.
Doing requests for AJAX requests for JavaScript is different then requesting JSON. Instead of requesting some data and parsing it you actually load the data and then eval it into the current page context through various tricks like appending script tags into the document. This is the actual Rails UJS implementation:
processResponse = (response, type) ->
if typeof response is 'string' and typeof type is 'string'
if type.match(/\bjson\b/)
try response = JSON.parse(response)
else if type.match(/\b(?:java|ecma)script\b/)
script = document.createElement('script')
script.setAttribute('nonce', cspNonce())
script.text = response
document.head.appendChild(script).parentNode.removeChild(script)
else if type.match(/\b(xml|html|svg)\b/)
parser = new DOMParser()
type = type.replace(/;.+/, '') # remove something like ';charset=utf-8'
try response = parser.parseFromString(response, type)
response
This is basically how we used to do AJAX calls cross domain ten years ago with JSONP to get around the limitations of the browsers of the day.
You can emulate the same thing in a "raw ajax request" with:
let xhttp = new XMLHttpRequest();
const url = "/users";
xhttp.open("POST", url);
// Some other things added to it...
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
let script = document.createElement('script');
script.innerHTML = data;
document.querySelector('head').appendChild(script);
}
};
But quite frankly js.erb is a horrible idea. It makes an absolute mess out of the server and client side responibilities and makes your code very difficult to follow and reason about and it moves JS out of the assets/webpack pipeline and into a smattering of proceedural junk script views. The only possible reason to use it is how lazy you can be with Rails UJS and still add some ajax to your application.
If you're writing an ajax handler anyways just return a chunk of html (in a json object or as html) and append it to the DOM instead.

Rails4: Passing non-forum data from front end to the back end, and processing it

Ok. So I have a small XHR request where json is returned. On success the json is passed like this.
var myArr = JSON.parse(xmlhttp.responseText);
myMainFunction(myArr);
function myMainFunction(arr) {
var vShipTypeID = arr[0].victim.shipTypeID;
}
I need to send vShipTypeID to rails. My goal is to be sending this value back to activerecord and the information returned will go within a js, or json file to the respond_to statement in the controller.
#shipName = InvType.find(vShipTypeID).name
Here's the main idea. The client sends out the ID of the ship to rails, and rails returns the ship's name.
I know how to make the Ajax request.
I don't know how to process the request on the server end. Meaning after rails receives the data, where do I find it, and how to I convert it to be usable so that I can make an activerecord statement out of the value I received from the client?
Anyone?
A simple solution could be defining an action on your ship controller and define a route to it for example define a route in your routes.rb
get "/ship/:id/getname" => "ship#getname"
in your js file
$.get( "/ship/"+vShipID+"/getname")
.done(function(data) {
alert( "Ship name: " + data.name );
})
.fail(function() {
alert( "error" );
});
in you ship_controller.rb
class ship_controller <ApplicationController
....... #other methods
def getname
#shipname = Ship.find(params[:id]).name
if request.xhr
render :json => {name: #shipname} and return
else
redirect_to ship_path(params[:id])
end
end
........ #some other methods
end
You need to handle json requests in your controller check this question for details
for a quick example in your controller create a new action getnamefromid and call that controller from your client.
respond_to do |format|
format.json { render :json => #shipName }
end

I'm a little unclear how the controller knows to return a JS file rather than HTML (from Railscast #174 Pagination)

In this Railscast #174 Pagination tutorial, the author changes...
$(function() {
$(".pagination a").click(function() { // e.g. a.href = /transactions?page=x
$.get(this.href, null, null, "script");
return false;
});
});
When my controller receives this request it returns the JS file (index.js.erb - I added this myself in accordance with the tutorial). I understand that the "script" paramater makes the difference but I can't find out what is happening.
Controller:
def index
# fetch arrays
#funds = current_user.funds
# set session vars
set_filter_date_session_variable(:transactions_filter_date_from) # to db format
set_filter_date_session_variable(:transactions_filter_date_to) # to db format
if #fund = current_fund
#transactions = #fund.transactions
.where("date >= ? AND date <= ? AND amount < 0", session[:transactions_filter_date_from], session[:transactions_filter_date_to])
.order("date DESC, id DESC")
## perform a paginated query:
#transactions = #transactions.paginate(:page => params[:page], :per_page => 5)
else
#transactions = []
end
#categories = current_user.categories.order(:name)
#transactions_filter_date_from = convert_date(session[:transactions_filter_date_from], "%Y-%m-%d", "%d/%m/%Y")
#transactions_filter_date_to = convert_date(session[:transactions_filter_date_to], "%Y-%m-%d", "%d/%m/%Y")
end
Does the "script" parameter get passed in the request header? Previously I thought the controller looked at the requesting file extension, perhaps default was .html (so if I request file.json it knows from the extension that it should return the json view). Could someone please clarify a little, or direct me somewhere I can understand how a controller handles which view to return in this case. I'd like to understand this part fully.
Thanks
With the
$.get(this.href, null, null, "script");
You're requesting from the serve that it returns the javascript file, hence why the "script"
Normally you will notice that at times people include the format.js in the controller so that when you put in the url + "." + "format type" (eg. reports.csv or reports.html) you'd need to include in the controller the code below (you can't just request json if your controller is not setup to bring back that information)
respond_to do |format|
format.html
format.js
end
In your case that you didn't include that format in the controller, the "script" in your get function above is asking to respond with the js file. Hence why your js code becomes executed and not your html. If you asked for html, see what happens.
Hope that makes sense?
I deduced to this conclusion because for my pagination I am using jQuery's function getScript which looks like this:
$.getScript(this.href);

How to pull a record with AJAX

On my site I have a simple model called Feed.
I want to make a link/button that will pull the Feed record with id=5 (for example) using AJAX.
The record that has been pulled should be displayed in a partial.
How can I do that ?
Thanks,
Oded
If you use jQuery, you could do sth like this:
In your controller you must respond to ajax request using the respond_to :js. Then you could either render directyl javascript which will be executed on your site, or the way I suggest you, to render json and parse it on the client side.
class YourController < ApplicationController
def index
#model = YourModel.all
respond_to do |format|
format.html
format.json {
render :json => #model.to_json
}
end
end
On the client side, just bind a click handler and then fetch the data using the path to your controller:
$("#your_link_id").click(function() {
$.getJSON('/path_to_your_controller', function(data) {
console.log(data);
});
}
The code is not tested, but it should work in that way.
Note: the console.log works with firefox but not with safari, try using firebug for console output.
Kind of long for a SO answer, but this should get you going:
http://www.tutorialspoint.com/ruby-on-rails-2.1/rails-and-ajax.htm
That's where I got started with AJAX on RAILS

Calling Rails update Method via Inline Edit

I was putting together a quick inline editing feature in my first Rails app and just as I was getting it working it occurred to me that I may be violating RESTful principles. The edit updated an image name. To do so, it submits, via PUT to Image#update and passes the new modified name as image[name].
The database gets updated properly, but I need that value back so that my markup can reflect the name change. To do that, I was calling /images/:id.json, but that got me wondering whether a PUT request can "validly" (in that RESTful sort of way) return a value like this.
Thoughts?
Update: For whatever it's worth, I'm using jQuery and the jEditable plugin to do the inline editing. Here's my jEditable code:
$(document).ready( function() {
$('h2').editable(
'/images/' + $('#image-id').val() + '.json',
{
method: 'PUT',
name: 'image[name]',
submitdata: { authenticity_token: $('#auth-token').val() },
submit: 'Save',
cancel: 'Cancel'
}
);
})
And my Image#update method as it exists right now:
def update
#image = Image.find( params[:id] )
if #image.update_attributes( params[:image] )
flash[:notice] = "Successfully updated image."
respond_to do |format|
format.html { redirect_to #image }
format.json { render :json => #image.to_json }
end
else
render :action => 'edit'
end
end
If your concern is just that your update method with JSON provide a response body and not just a 200 OK (Rails's head :ok) then I don't think you need to be worried. The default response is 200 OK so the only difference between what you're doing and what Rails does by default (in its scaffolds) is that you're also including a response body. As far as I can tell proper REST etiquette only requires that you return a 200 OK and doesn't care about the response body, which is in line with what you're doing.
Beyond that all your code looks excellent.

Resources