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.
Related
I have a folder on the server named uploads where uploaded files are stored (images) on requests made to the server to get a file I want to verify if the user has purchased it.
Ids of purchased products by the user are stored on a user object in MongoDB.
So I think that I should somehow attach the product id to the request or URL to then check if it exists in the user object, but where to attach it and how or maybe there is a better solution how would you tackle that?
As you already using MongoDB (even though I would suggest a relational DB for this case), I believe one approach would be to create a "middle" table called "purchased_images", linking the user_id with the image_id.
In the frontend you can write an ajax to pass the userid and itemid .You must session to do this.
when the user click verifyItembutton you can call a function by something like this
<button onclick="checkItem(userid,productId)">verifyItem</button>
Then in your script file you can call ajax
function checkItem(userid,proId) {
let data = {
userid,
proId,
}
$.ajax({
type: "post",
url: "/foo",
data: data,
success: function (response) {
console.log(response);
}
});
}
Now in your route file you can add a route /foo and you can perform mongo queries to find whether the user own it and return a boolean value the value will be sent to client side ajax and you can do whatever you need based on the state in success function of ajax
hope it helped you feel free to ask any doubts !
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');
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.
I'm taking an input from user named as category. On every key up i want to perform an ajax request to search if category with the similar name exists or not. If yes, then a there is a blank div below that input which i want to fill with the similar name categories.
So i created a form. Used ajax via jquery but i'm not receiving the response.
This is the jquery ajax code that i'm using
$("#category").keyup(function () {
$.ajax({
url: "categories/categoryajaxrequest",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
This is the route part which is used as url in ajax request
Route::get('categories/categoryajaxrequest', array('as' =>'categoryajaxrequest', 'uses' =>'CategoryController#categoryAjaxRequest'));
and this is the controller part
//app/controllers/CategoryController.php
....
public function categoryAjaxRequest(){
echo "working";
}
So, the input text has an id of "category" and below the input, there is a div with an id of "category_suggestion". At every keyup on the input, i expect it to perform an ajax request and show "success" in div . But it's not doing anything.
However, if i go directly to "/categories/categoryajaxrequest" on my browser, it outputs "working".
Try putting the action directly in the url: property of the $.ajax() method, then no route is needed:
Laravel gives us the liberty to do that. The curly braces {{ }} are used in views. As the JavaScript stuff is usually called in a view, it is legitim to do it that way.
The URL::action part is described in the docs as follows:
To generate a URL to a controller action, we may use the URL::action
method or the action helper method:
$url = URL::action('FooController#method');
$url = action('FooController#method');
So the combination of the template system & the URL::action gives us the possibility of doing it this way:
$("#category").keyup(function () {
$.ajax({
url: "{{URL::action('CategoryController#categoryAjaxRequest')}}",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
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.