What should I name the actions for ajax requests? - ajax

Let's say I have an action:
def result = Action { Ok(views.html.home.result()) }
From result view I want to send ajax requests to the server. What's the standard (if any) way to name the actions that receive such the ajax requests? It might be something like:
def getResultAjax(param1: Int) = //....
To my mind, it look clumsy.
Your ideas?

There's no such convention in Play, anyway action's name should rather contain info about returned data i.e. listOfBooks then just getResult.
On the other hand when there's a lot of different methods (some common, other for ajax requests) it can be cleaner if you'll use ajaxListOfBooks or create BooksAjax controller to handle AJAX request only.
BTW: Purists would say that the requests REST's HTTP methods should also be taken into account, and then action names can be simplified, pseudo routes:
GET /ajax/books Books.list
GET /ajax/books/:id Books.get(id)
PUT /ajax/books Books.create
POST /ajax/books/:id Books.update(id)

Related

Is it better to retrieve data through AJAX or returning it alongside view from Controller (Laravel)?

So the scenario is getting data we need from controller and using it in our view. But there are two options, you can have either this line in your "show" method:
UserController#show
return view('webpage');
And in the 'webpage' you can send an Ajax request to UserController#fetch and get that data. Or you can get the data from database in UserController#show and then send it alongside view like this:
UserController#show
return view('store', compact('store'));
But which is the more efficient and secure way of doing this?
It really depends on what you're doing, if the data you're requesting and the process you're running takes a lot of time or in a future it would, ajax is the way to go, but if process is short and the requested data from your model is small, then you can request it on the same method that returns your view and send the data to it.

HTTP Requests in Laravel

In Laravel we use routes to deal with HTTP requests from the browser.
We can route a request to a controller, do some logic and then return a response.
Now, we can send in variables encapsulated with braces {} and the response can be anything, so it seems to me that routing through a controller means that the the properties of the different request methods (POST, GET, PUT etc.) are lost.
For example I could send a POST request with URI example/{id} then put in my routes.php file
Route::post('example/{id}','SomeController#SomeAction');
Then I could do something in my controller with the variable $id and send a response.
On the other hand I could send a GET request with URI example/{id} and alter my route to
Route::get('example/{id}','SomeController#SomeAction');
The controller would give the same response.
So, am I right in thinking it does not really matter what request method is used?
Two parts of your question I can identify on a second read-through:
Request methods are not lost. You have access to them with $request->getMethod(). So a GET request will return GET. You also have the method isMethod('GET') available to you, which you could use to get a truthy value which would enable you to return a different kind of response depending on the request type.
With regards to the way you set up your URL, what HTTP verb you use does matter if you're creating a REST-ful web service.
I won't explain away what a REST-ful web service is (you can look it up), here is a couple of points from your example:
If you're getting some data, you ought to be doing a GET request. It is the verb to represent a read from a resource. If you had to send a lot of data - and your intention is to add data, you ought to POST it instead.
The URI should be meaningful in a way that best describes the resource you are manipulating.
Together with the HTTP verb, you can infer the implied action. So if you are POSTing to example/1, I might infer that (and this is a digression, actually) that you are attempting to update record 1 from an example resource. In reality, you would perhaps use the PUT verb (which handles update).
Behind the scenes, Laravel uses a POST request due to browser limitations but treats it as a PUT request server-side.
Of course request type does matter. When you want to hide some request data against user and dont show it in url for example:
?username="Admin"&nick="admin1" then u will use POST otherwise you can use GET. When you want get some data u will use GET but when you want to send some data then you should use POST instead.

Convention for a controller that generates a view from several models

In Sails.js, a route is set up against a controller method which can render a view. For the most part, this is straightforward, i.e. you could set up a GET /users route that points to UserController.find (which is usually set up automatically anyway).
However, say the home page of a blog renders the 10 most recent posts in the main section and a column with a list of authors and categories. The controller method has to fetch posts, authors, and categories before rendering the view and sending it back to the client. Clearly, a method like this doesn't really belong in PostController, AuthorController, or CategoryController.
What's the best thing to do in this situation? Create a controller for rendering views that rely on data from multiple models? Is there a good name for such a controller?
Thanks!
What I would do (this is purely opinion-based) is creating a PageController and create an action for each page you'd want.
For your home page example you can create a home action, get whatever you need and then render it with res.ok() (if everything is fine).
Another option would be to use Sails as a pure API and use HTTP requests (Ajax) or sockets to get your data in JSON. If you want to do so, I'd advise you to use a front end framework such as Angular, Ember, React...
By the way you could also create actions rendering HTML in your existing controllers and create a route to hit them through Ajax requests and just print them in your page. I'd prefer the 2nd solution because it takes full advantage of the Blueprint API (you don't need new controller or action whatsoever).
As Yann pointed out, this answer has to be a little opinionated. It seems that you are using the views system and not building a single page application. For the home page, I would go for an IndexController.js file with a home(req, res) action.
// api/controllers/IndexController.js
module.exports = {
home: function (req, res) {
// Retrieve all the information you need
// Take care about managing the asynchronous calls before rendering the view
return res.view('homepage');
}
};
Declare the route
// config/routes.js
module.exports.routes = {
'get /': 'IndexController.home'
}
Create the view in views/homepage.ejs.

Django: Is it possible create and send Json from a view to another server?

If i have a link like this one Get User Data who points in a view inside my own server, is there any way to send a json object (maybe just maybe with ajax?) to another external server and retrieve an answer? Something like this:
from django.shortcuts import render
def profile(request):
#send a json object to another server like http://www.myotherserver.com/user
#get the answer and process it
return render(request, 'accounts/profile.html' ,
{'profile_user': data_from_the_external_server})
The above i can implement it of course with jquery-ajax but i just was wondering if i can do it this way...
Thanks in advance.
Of course you can. Why wouldn't it be possible?
Don't code this in AJAX if that's not necessary.
There are 2 things you need, you need to prepare the JSon to send and then you need to send it to the API you want:
Look at "simplejson" to create the json data to send.
Look at "urllib" to send a request to another server in Python (like here: How to send a POST request using django?)
Also do not put it straight in your view. Create a new class for it. So in your view you'll have something like that:
def profile(request):
# instantiate your service here (better with DI)
profile_user = my_service.get_profile_user()
return render(
request,
'accounts/profile.html' ,
{
'profile_user': profile_user
}
)
If you need to send HTTP data (via a POST or GET) to another server and receive a result from within your view, you can use Python's urllib2 library. However there is an easier third party library called Requests which can handle this task for you.

RESTful URLs: "Impractical" Requests, and Requiring One of Two Request Parameters

I have a RESTful URL that requires either the offset or the prefix request parameter (but not both).
GET /users?offset=0&count=20
GET /users?prefix=J&count=20
What's the best way to enforce this rule? Spring has the #RequestParam annotation with the 'required' property for optional parameters, but I want to enforce an "either-or" rule on these two parameters. I know I could do it in the code, but is there another way to do it?
Also, what's the proper way to handle "impractical" requests? Say I have 100 million users; the following request, although properly RESTful, is not something I want to support:
GET /users <-- Gets all 100 million users, crashes server and browser!
What should I send back?
You can create two methods and choose one of them with #RequestMapping's params attribute:
#RequestMapping(..., params = {"prefix", "!offset"})
public String usersWithPrefix(#RequestParam("prefix") ...) { ... }
#RequestMapping(..., params = {"offset", "!prefix"})
public String usersWithOffset(#RequestParam("offset") ...) { ... }
what's the proper way to handle "impractical" requests?
The lesser-practiced principles of REST include the requirement that resources be "discoverable". If you are asked for a complete list of 800 million users and you don't want to provide it, you might instead consider serving a page that describes in some way how to filter the collection: for example, an XForms document or HTML containing a FORM element with fields for offset/prefix/count, or a URI template with the appropriate parameters
Or you could just send a "413 Entity too large" error - edit: no you can't. Sorry, I misread the description of whath this code is for
If you decide to go down the route of just sending the first page, I think I would send it as an HTTP redirect to /users?offset=0&count=20 so that the client has a better idea they've not got the full collection (and if your response contains a link to access subsequent pages, even better)

Resources