ajax call redirect to page - ruby-on-rails

In my server terminal I saw Started GET "/another" but the browser dont redirect to the url. What is wrong in this code?
Routes:
match '/example_url', to: 'controllerx#sup', via: 'get'
Client side:
$.ajax({
type: "GET",// GET in place of POST
contentType: "application/json; charset=utf-8",
url: "/example_url",
data : {example: 'hey'},
success: function(result) {
//TODO
},
error: errorFunction
});
Controller:
def sup
respond_to do |format|
format.js { redirect_to another_path }
end
end

You not able to redirect from the controller action because action called remotely.
Try this:
Client:
$.ajax({
type: "GET",// GET in place of POST
dataType: "json",
url: "/example_url",
headers: {
'Content-Type': 'application/json'
},
data : {example: 'hey'},
success: function(result) {
window.location = result.location;
},
error: errorFunction
});
Controller:
def sup
respond_to do |format|
format.json { render json: { location: another_path } }
end
end

Related

Passing in rails routes to AJAX url value

I have an app where a user has a portfolio that has many positions and each position has many movements. So the url for an associated movement index page for a particular position looks like: portfolio_position_movements. I have an index page with and the controller action looks like
def index
#movements = #position.movements.all
respond_to do |format|
format.html
format.json { render json: #movements}
end
end
My ajax call in my movements.js file is this:
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: ?,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
How can I pass in a dynamic route path so this will work with the movement index on any position object?
You can use erb tags in js files, for me i did it as the following:
#edit.js.erb
$modal = $('.modal'),
$modalBody = $('.modal .modal-body'),
$modalHeading = $('.modal .modal-heading');
$modalHeading.html("Edit <%= #student.full_name.titleize %>'s information");
$modalBody.html("<%= escape_javascript(render 'edit_student') %>");
$modal.modal();
Note: the file extension is .js.erb so rails can process it. I was calling a modal form and the edit method in students_controller.rb was:
def edit
#student = Student.find(params[:id])
respond_to do |format|
format.html # edit.html.erb
format.js # edit.js.erb
format.json { render json: #student }
end
end
Edit:
You can embed the JS code inside html.erb and use rails routes like:
<script>
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: <%= my_ajax_path %>,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
</script>
What is my_ajax_path?
Is a rails route defined in routes.rb for example i need a list of all available sections that students can apply to using ajax so i did the following:
1- defined a method in students_controllers.rb like this one:
def available_sections
batch_id = (params[:batch_id].nil? || params[:batch_id].empty?) ? 0 : params[:batch_id].to_i
if batch_id == 0
#sections = [].insert(0, "Select Section")
else
batch = Batch.find(params[:batch_id])
# map to name and id for use in our options_for_select
#sections = batch.sections.map{|a| [a.section_name, a.id]}
end
end
2- added a route to it in routes.rb
resources :students do
collection do
get :available_sections
post :create_multiple
end
end
3- Inside new.html.erb:
<script type="text/javascript">
$(document).ready(function() {
$('.student_section_id').hide();
$('#student_batch').change(function() {
$.ajax({
url: "/students/available_sections",
data: {
batch_id : $('#student_batch').val()
},
dataType: "script",
success: function () {
if (+$('#student_batch').val() > 0)
{
$('.student_section_id').fadeIn();
}
else
{
$('.student_section_id').fadeOut();
}
}
});
});
});
</script>
Forget about that messy code :D as it was my first steps but you get the point, and for this line url: "/students/available_sections" it should be using rails routes you can get it by calling rails routes from the command line to get a list of all your application routes

Ajax on Ror, Networkerror

I'm working in a simple increment fonction who is not working. In my console I have this error "NetworkError: 404 Not Found - ..../test/increment_nbr" and I'm not able to fix it.
Html:
<button id="incr">AJAX2</button>
<script>
$("#incr").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "/test/increment_nbr",
dataType: "json",
type: "POST",
success: function(data) {
}
});
})
</script>
My controller:
respond_to :html, :json
def increment_nbr
#user = User.find(params[:id])
#user.increment! :nbr_set
render json: { nbr: #user.nbr_set }.to_json
end
Routes:
resources :test do
member do
put :increment_nbr
post :increment_nbr
end
end
Your routing is incorrect - you've defined your two increment_nbr routes as member routes, meaning they operate on an instance of your parent test route and would generate URLs like /test/2/increment_nbr.
See http://guides.rubyonrails.org/routing.html#adding-more-restful-actions for more information

Ajax call is returning error from action controller in rails

on change of a dropdown value i am trying to populate other dropdown list value.
Here i have added my new action in routes.rb :
resources :appointments do
collection do
get :getdata
end
end
This is my js code :
$("#appointment_department_id").change(function(){
//on change of department dropdown.
$.ajax({
url: "/appointment/getdata",
type: "GET",
data: {department_id: $(this).val()},
success: function(data){
alert(data);
}
error: function(data){
alert(data);
}
});
});
here is my action in controller file :
def getdata
#dept_id = params[:department_id]
department_name = #dept_id
#all_doctors = User.all; #will write my custom query later.
end
But on call to this action, it's returning error:
"NetworkError: 404 Not Found - http://localhost:3000/appointment/getdata?department_id=5"
(checked in firebug)
the error is in the ajax url, in the ajax request you are using 'appointment/getdata', but in routes you have defined appointments,
so use
$("#appointment_department_id").change(function(){
//on change of department dropdown.
$.ajax({
**url: "/appointments/getdata",**
type: "GET",
data: {department_id: $(this).val()},
success: function(data){
alert(data);
}
error: function(data){
alert(data);
}
});
});
Where's your respond_to in your controller?
If you're sending an Ajax request, you'll have to either define respond_to "JS" or "JSON" like this:
def getdata
respond_to do |format|
format.js
end
end
You could also do it like this:
Class Controller
respond_to :html,:js, :json
def getdata
respond_with(#custom_vars)
end
end
i think you forget "s" of "appointment" word in url: "/appointment/getdata", so try to add "s" like this :
$.ajax({
url: "/appointments/getdata",
...
...

Rails , Ajax , Post Function , Jquery

I am working on Rails and having problem with ajax post data call. It is working and data is entered in db but the SUCCESS function is not working, as alert function in success function is not firing.
Further I want to add comment to my post without refreshing whole page.
AJAX code looks like :
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '/comments/create',
type: "POST",
dataType: 'json',
processData: false,
success: function (msg) {
alert(msg);
},
error: function (xhr, status) {
alert(xhr.error);
}
});
});
});
</script>
and Controller code is :
def create
puts 'params', params.inspect
#post = Post.find(params[:post_id])
#comment = #post.comments.new(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to(#post, :notice => 'Thanks for comment.') }
format.json { render json => #post, :msg=>"comment oK" }
else
format.html { render :action => "new" }
format.json { render :xml => #comment.errors, :msg=>"comment oooK", :status => :unprocessable_entity }
end
end
end
This code works fine to post the data to the create function, which creates (posts?) the entry to the db. But I would like to return the data in the alert function upon "success" but alert in success function is not working and alert in error function is firing.
Try:
$('form').submit(function()
{
var myForm = $('form').serialize();
$.ajax
({
url:'/comments/create',
type:"POST",
dataType:'json',
data: myForm,
processData:false,
success: function (msg)
{
alert(msg);
},
error: function (xhr, status)
{
alert(xhr.error);
}
});
});
If this doesn't work, please write what you're sending across the wire in your AJAX request. Use Chrome Console or Firebug to check and paste the POST results in here.

Getting 2 variables from 1 ajax call in ruby on rails

I was wondering how you can get 2 variables to update a div tag using an ajax call instead of just 1. My current .js file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data);
}
});
});
});
show.html.erb where i get the data:
<%= #product.item %>
I would like something like this
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data[1]);
$("#price").empty().append(data[2]);
}
});
with
<%= #product.item %>
<%= #product.price %>
where my description div gets updated with #product.item and my price div gets updated with #product.price. How could I achieve this?
EDIT
updated .js file
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "json",
success: function(data) {
$("#description").empty().append(product.item);
$("#price").empty().append(product.price)
}
});
});
});
show.html.erb:
<%= #product.item %>
<%= #product.price %>
controller:
class ProductsController < ApplicationController
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
def index
end
def show
#product = Product.find(params[:id])
end
end
I'm pretty sure that controller isn't correct. I placed #product before respond_to and it didn't work so I just put respond_to without really knowing where it goes. Sorry for being such a noob. Thanks for all your help.
FINAL EDIT:
working javascript file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.getJSON("/products/"+selected_product_id,function(data){
$("#description").empty().append(data.item);
$("#price").empty().append(data.price);
});
});
});
Ah, This remembers me a piece of code I wrote for you a week ago!
You can use JSON to render your Product:
#controller
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
end
And handle the response from the server like this:
$.ajax({
url: "/products/" + selected_product_id,
dataType: 'JSON',
success: function(data) {
var product = JSON.parse(data);
$("#description").empty().append(product.item);
$("#price").empty().append(product.price);
}
});
Edit #1: I found this method: jQuery.getJSON : http://api.jquery.com/jQuery.getJSON/
You could use JSON, return
{"item": "<%=j #product.item %>", "price": <%= #produce.price %>}
then type: 'json' in the ajax call

Resources