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.
Related
I have an instance variable, #source_code in my Rails controller that I want to retrieve in my Ajax response via the success function. I am calling this Ajax function from my index.html.erb file and it renders a show.html.erb file. I want to get my text area to print out the #source_code.code value.
SourcesController.rb
def show
Rails.logger.debug("REACHED: show >>")
#source_code = Source.find_by(id: params[:id])
Rails.logger.debug("REACHED: source_code >>" + #source_code.code.to_s)
#sources = Source.all
end
index.html.erb
function updateTextArea(source_id){
console.log(source_id);
$.ajax({
type: "GET",
url: "/sources/" + source_id,
data: {source_id: source_id},
success: function (response){
alert("Ajax success")
console.log("<%= #source_code %>");
editor.session.setValue("<%= #source_code %>");
},
error: function(){
alert("Ajax error!")
}
});
Expanding on Nycen's answer, you first want your controller handle the ajax request and return a JSON response:
def show
respond_to do |format|
format.json { render json: Source.find_by(id: params[:id]) }
end
end
PS: Take care with that, it will send all of the fields of your Source record down the wire. I call slice (see ActiveRecord.slice()) on the model to limit the fields returned in the JSON.
Then your JavaSript needs to use the JSON result of that ajax call:
function updateTextArea(source_id){
console.log(source_id);
$.ajax({
type: "GET",
url: "/sources/" + source_id,
success: function (response){
alert("Ajax success")
console.log(response.code);
editor.session.setValue(response.code);
},
error: function(){
alert("Ajax error!")
}
});
It depends on how your routes are setup, but there should be no need to set the data property in the Ajax call. Your route is likely to pull it from the URL path: /sources/12345.
Note there is no show.html.erb with this setup. There is no view, your controller just returns JSON.
You're expecting your success handler to have access to #source_code just like a "show.html.erb" view would, but it doesn't work that way.
When you use ajax, the method is called from the browser; it's a piece of code you send away from your server, it can still interact with it, but it doesn't have access to the controller variables.
So, your show action needs to render something your handler can understand, for instance json. Then you'll have access to it in your success by reading your "response" variable.
This is my ajax handling code:
$.ajax({
url: "shirts/first?page=" + params[:page],
type: "GET"
})
How to tell Ajax to take the results from the next page in the shirts/first file?
I wrote the code as I've shown but it throws a error saying 'syntax error'! How can I solve this?
Also my .js.erb file if its of some help:
$("#container1").append("<%= escape_javascript(render 'shirts/first')%>");
If you're performing ajax pagination, you'll have to ensure you can handle the Ajax request on the controller (using respond_to), and send the correct data:
JS
#app/assets/javascripts/application.js
$("a.pages").on("click", function() {
$.ajax({
url: "shirts/first?page=" + $(this).attr("id"),
type: "GET"
});
});
You'd need to have your pagination buttons with the page's ID for this
Controller
#app/controllers/shirts_controller.rb
def first
#shirts = Shirt.where(your_query)
respond_to do |format|
format.html
format.js
end
end
View
#app/views/shirts/first.js.erb
$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");
you have mixed the rails params and javascript code, in javascript
url: "shirts/first?page=" + params[:page]
has syntax error because of : charachter, and even if you remove it means you have a javascript object named params and page is a variable which refers to a key in the params object, whereas here params[:page] refers to a querystring which its key is page in the current request from the client.
So change it like:
$.ajax({
url: "shirts/first?page=<%= params[:page] %>",
type: "GET"
});
You have to be careful here, cause the code above means the current page is being loaded with the page in its querystrings like: http://example.com/homepage?page=helloworld and helloworld probably is the other page in your story.
and for your .js.erb file, in rails 3.0.8, you have to wrap every escape_javascript call with raw():
$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");
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.
I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1 :
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
The same origin policy prevents you from using client side JavaScript to directly discover information about arbitrary URIs (URIs you control are a different story).
You'll need to get that information with another technology, such as your server side Ruby.
You could do this by simply submitting a form to the server and returning a new webpage to the browser.
If you don't want to leave the page, then you can pass the data using Ajax. There are no shortage of Ajax tutorials out there, here is a good one from MDN.
Here's an example of an AJAX call:
$(document).ready(function () {
$("#button_check").on("click", function () {
$.ajax({
type: "GET",
url: "Your URL",
data: {
input_url: $("#textbox_id").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
});
Where your HTML is something like:
<input type="text" id="textbox_id" />
<input type="button" id="button_check" value="Submit" />
And your Ruby code would be something like:
require 'open-uri'
class TestController < ApplicationController
def index
req = open(params[:input_url])
render :text => req.content_type
end
end
I have never used RoR before, so I have no idea if this is right or works in the slightest. But it's what I could quickly conjure up when scrambling through several tutorials. It's simply the concept you seem to be looking for. You'll need to figure out how to map a URL to this method, and then update the AJAX option url to use that.
So in the Javascript code - in the done method, that means the whole AJAX request was successful and the data variable should contain the result from the Ruby code req.content_type.
Atlast I could figure out the whole thing with the great help of #Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.
I've been googling all day and still couldn't find any answers.So basically in my javascript function, I want to send a GET request to my rails controller and the rails controller will send back a JSON object. Any idea how do I do this? thnx
Using jQuery I would do something like this:
In the selector and event you want, for instance on clicking some element:
$(function() {
$('#foo').click( function(){
var params = '{"field1": "value1", "field2: "value2"}';
$.get('/controller/bar', params, function(data){
alert(data);
});
});
});
Then in your Rails controller:
def bar
/// hack hack hack
render :json => {"response" => "OK"}
end
The in your routes.rb:
match 'controller/bar' => 'controller#bar'
Finally, change "controller" according to your code. Firebug is your friend!
you can use jQuery ajax to make get or post request from javascript.
jQuery.ajax({
url: "url to controller method", // it should be mapped in routes.rb in rails
type: "GET",
data: {field1 :value1, field2:value2}, // if you want to send some data.
dataType: "json"
success: function(data){
// data will be the response object(json)
}
});
response from rails will something similar to the below, you can modify as per your requirement.
respond_to do |format|
format.js { render :json => #json_data }
end