In a Ruby on Rails application, I want to be able to place a User's username in a input text box, press an 'Add' button, and have them appear underneath with their details. Then, I can simply remove them from the list if I want using another button.
How does one connect Javascript and Rails database to complete such a task specifically with those buttons? While Javascript isn't a strength of mine, I'm more puzzled by how to extract and modify the Rails database using Javascript. For reference, I'm also using MongoDB.
What would be the best way to approach this?
Here is the jQuery and AJAX code that I'm using to 'POST' to the server endpoint 'admin/popular/users.json', but I'm not sure how to get Rails to create a new user in the database using my Popular::User model.
$(document).ready(function() {
$('.add-to-popular-users-button').click(function(event){
event.preventDefault();
var addToPopularUsersBtn = $(this);
var userToBeAdded = $('input[name=popular_user]').val();
var data = { 'popular_user': {'username': userToBeAdded, 'category': 'popular'} };
var url = "/admin/popular/users.json";
$.ajax({
url: url,
data: data,
dataType: 'json',
type: 'POST',
success: function(e) {
alert('Great success!');
}
});
});
});
Here's my Popular::User model:
class Popular::User
include Mongoid::Document
include Mongoid::Timestamps
POPULAR = 'popular'
field :category, default: POPULAR
index :user_id
belongs_to :user
validates_presence_of :user_id
validates_uniqueness_of :user_id
def self.popular
user_ids = self.where( :category => POPULAR ).map(&:id)
User.where(:_id.in => user_ids)
end
I am not familiar with rails framework, but you can do it using ajax. You can send an ajax post request to controller method which will creae a user, create a table row(or recreate the table), and returnd html place in table.
A simple example is:
$.ajax({
type:'post',
data:{} //user data,
dataType: 'json', //or any other
url: 'page_or_method', //page or method that will return html
success: function (data) {
$('div#userTable').html(data); //in case data contains the table
}
});
Read about $.ajax method (jQuery), or you can use XMLHttpRequest if you don't whant to use jQuery.
So, I was able to figure this out with a bit of testing. But, basically, you can either do this with AJAX/jQuery or with Rails inherent RESTful architecture, i.e., HTTP verbs like calling :delete, and associating it with a particular UI button.
One important idea that you should recognize with AJAX is that whatever data you send to the right server endpoint with a 'POST' or 'DELETE' verb or what have you, it will get picked up by the appropriate controller action. In other words, if I'm sending data via 'POST' to the '/popular/users.json' endpoint to create something, the def create method will be able to manipulate data afterwards. Then, you can assign the data to an ivar in the controller action to be interpreted and manipulated in the UI view corresponding to the controller action.
Related
I am coding some basic crud application in Symfony2 where I want to implement some type of search function on a certain page.
The idea is that I want to launch a search query by entering something in an inputfield which is going to fire an ajaxcall (I could not think of anything better). The response of that ajaxcall has to be a kind of popup list with clickable items that is placed into another field on the initial page when clicking an item.
I have two questions:
Is there a better approach than ajax and how can I resolve the problem of the 'popup list' thing.
Second: I can make post ajaxcalls in Symfony2 with this kind of code:
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "post",
success: function(data) {
//some things here
}
But I thought it is a bit strange to use post and I wanted to use get.. Apparently this is not working as I can not retrieve my data in the controller..
EDIT: I forgot to post my controller where I am handling the ajax call, here is the code:
public function testGetAction(Request $request)
{
$data = $request->request->get('data');
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('EuropsimProductBundle:SimProfile')->find($data);
return new Response($entity); }
This is working fine with method: "post", but failing when I try to use "get".
I also read about typeahead and this is really close to what I meant, the thing is I want a custom little popup or something because the ajax is supposed to return an array of objects with multiple attributes that has to be shown and where mulitple items are selectable. You can see it as two steps where you first launch the searchquery which bring you to a kind of popup or something where you can select the desired rows for further use on the page.
Thanks in advance!
Hicy
You have to use method $request->query:
For GET method:
$data = $request->query->get('data');
For POST method:
$data = $request->request->get('data');
This really is not much a Symfony2 related question... but...
This code is javascript, if you want to use GET just change method to GET,
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "get",
success: function(data) {
//some things here
}
Then in Symfony create the route test_oostand do whatever you want on the controller to send "data" in the response.
Then on te success method process this data accordingly and create the needed view.
EDIT: Based on your new edit, you have an error accessing your data parameter, you should use query instead request
$data = $request->query->get('data');
I am working on Symfony2 project. And now want to add some dynamic actions.
I want to use jQuery and Ajax calls and API.
Below I wrote my project model.
Issue is there where I put "?" on the picture.
For example I have comments in my page and 2 buttons "oldest" "newest".
Basically on the page load TWIG load comment to my view and everything works fine.
Then I want to click on the button to change way of display comments. But want to do this without reloading a page.
I click btn -> run JavaScript -> connect byt AJAX with API controller -> take back data from database ... And here I stuck
I have data in JSON but have no idea how to load them into my view instead a date loaded by Twig at the beginning.
That's a serious wall on my way to dynamic changes on web page.
Thinking about:
Creating all the view in JavaScript and replace twig data on the view using jQuery like .html() or something - but there would be a lot of HTML code in JavaScript script, not sure that's right way
Maybe you know how to solve that issue in more elegant way?
It is not a Twig, but a JQuery concern. Here is an example.
Route:
my_symfony_route:
path: /get-filtered-list
defaults: { _controller: "CompanyMyBundle:Comment:getFilteredList" }
methods: POST
Controller
public function getFilteredListAction(Request $request)
{
$param1= $request->request->get('param1');
$param2= $request->request->get('param2');
$result = array();
//Fill $result with DB request
return new JsonResponse($result);
}
JQuery request
$.ajax({
type: 'POST',
url: "{{ path('my_symfony_route') }}",
data: { param1: 'value', param2: 'value' },
dataType: 'json',
success: function (data) {
//Handle your JSON data to update the DOM
$.each(data, function(index, element) {
$('#myDivId').append($('<div>', {
text: element.name
}));
});
}
});
How can I in Rails write a Coffeescript function to update a database column? I guess an Ajax call of sorts would be ideal:
id = $('#document').attr('data-document-id')
$.ajax
url: "/documents/#{id}/update_attr"
type: "GET"
success: (data) ->
console.log(data)
Is something like this the only way? Or is there something better?
Well, keep in mind that frontend code (html, css, js) cannot access the database directly. So you need an AJAX request.
REST best practices would require you to use a POST/PUT/PATCH method instead of the GET method which should never change the state of the application.
Also, you are not passing any value to the Rails backend.
$.ajax
url: "/whatever/#{id}"
type 'POST'
data:
key: value
success: (data)->
console.log data
On the Rails side you need to setup the appropriate route in config/routes.rb:
post '/whatever/:id', to: 'some_controller#some_action'
Still ideally, following the best practices, you probably have some sort of
resources :apples
already mapped to an ApplesController. You now have to implement the action, which will be like this:
def update
#object = Whatever.find(params[:id])
if #object.update(key: params[:key]
render json: { success: 1 }
else
render json: { success: 0 }
end
end
That implementation is not complete (it does not handle HTML requests, multi-key updates and other fancy things), but still it should solve your problem.
How do I do a PUT, POST or DELETE call from javascript?
I've collected some data using jquery drag and drop. How do I then send this to the database? I think I might be able to use jQuery.ajax but can't work out how exactly.
Any pointers appreciated.
Solution:
This is the javascript that works
$(document).ready(function() {
$.ajax({
type: "PUT",
url: "/articles/8", // should be mapped in routes.rb
data: {articles:{name:"New Name"}}
});
});
But it doesn't change the name of article 8 to New Name. Firebug shows no errors, but I still can't pass data to the edit.
The url is the standard update using put url, it exists in the routes.
You can use jQuery ajax for this: It is a very good way to handle browser requests dynamically with server side code.
jQuery('#element_id').on('click change',function(){ // use event as per your need
$.ajax({
type: "GET",
url: "/edit_comment", // should be mapped in routes.rb
data: {comment:"new comment"},
datatype:"html", // check more option
success: function(data) {
// handle response data
},
async: true
});
});
For more details check these links:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/category/ajax/
RAILs code:
def edit_comment
#comment = params[:comment]
// store to database
response_to do |format|
render :html 'comment.html'
end
end
routes.rb
map.edit_comment "edit_comment", :controller => 'comment', :action => 'edit_comment'
For PUT and DELETE add an extra parameter named _method: _method=PUT
Rails uses it to simulate PUT and DELETE.
I currently have a city that someone will enter into the system and I want to go from my javascript action to a rails action so i can get the city.id from the database. For example
my javascript
function get_city(city){
//city comes in like "Washington DC"
}
my rails action
def return_city_id
#city = City.find_by_name(params["name"])
return #city.id
end
Try ajax. You can setup path in routes.rb like find_city_id_by_name?name=Washington DC. Then you can use jquery to send request.
$.ajax({
url: 'find_city_id_by_name',
data: {'name' : city},
dataType: 'text',
success: function(id) {
alert(id);
}
});
In controller, you'll need to write single id as request response:
render :text => id
More information:
http://api.jquery.com/jQuery.ajax/
Although what you ask is definitely doable, querying back-end each time you need to fetch city id by its name sounds like a bad idea to me. If the name itself come from back-end (for example, you have list of cities for user to choose from), it's better to provide ids together with names (not visible to user, but somewhere in html).
You have to use AJAX to call any methods on the server-side.
function get_city(city){
$.getJSON("/ajax/city_id", { "city" : city }, function(data)
{
//Do something with data
});
}
/ajax/city_id is some action in some controller that returns JSON when you call it.