Rails , Ajax , Post Function , Jquery - ruby-on-rails

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.

Related

How do I tell my Rails controller to use the format.json part of my method instead of the format.html branch?

I'm running Rails and trying to set up an autocomplete on my text field. I want to submit to a controller method. If I'm submitting from my form (using the "Submit" button), I'd like to use the "format.html" branch. If I'm submitting using the autocomplete Ajax call, I'd like to use the "format.json" branch ...
def search
if params.has_key?("s")
search = params[:s].strip
#people = Person.where("name ilike ?", "%#{search.upcase}%")
respond_to do |format|
format.html {
if #people.size == 1
redirect_to controller: 'votes', action: 'show', id: #people.first.id
end
}
format.json { #people.map(&:name) }
end
end
end
I set up the autocomplete on my text field like so
$(function() {
return $('#s').autocomplete({
source: function(request, response) {
$.get('/people/search', { s: request.term }, function(data) {
alert(data)
response(data.split('\n'));
});
}
});
});
but what's happening is the value of "data" is an HTML page, as if I were submitting via the format.html method. How do I configure things so that my autocomplete call forces me to render the JSON response from my controller?
Specify .json format in the url like this -
$.get('/people/search.json', { s: request.term }, function(data) {
alert(data)
response(data.split('\n'));
});
To send raw json data In Controller change. Otherwise it will look for template to build json (by default rails will look for search.json.jbuilder)
format.json { render json: {people: #people.pluck(:name)} }

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 call redirect to page

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

Ruby on rails Ajax call showing 404 error

I am making and ajax call to hit the controller but it is showing the 404 error:
My controller method is like:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
end
end
And my route for this is like:
post "user_time_checks/get_user_time"
And my ajax script is like:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.ajax({
url:"get_user_time?user="+user_id,
type:"POST",
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
}
}
Try this:
$.ajax({
url:"user_time_checks/get_user_time",
type:"POST",
data: {
user: user_id
},
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
Also make sure you really need to do POST method and that rails route does not require specific paramater like :user_id. Basically check the output from
rake routes | grep get_user_time
Your route should be:
post "user_time_checks/get_user_time" => "user_time_checks#get_user_time"
Also, since the purpose of the request is to get some data, you should make it a GET request instead. So:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.get("get_user_time",
{user: user_id})
.success(function(time) {
console.log(time);
})
.error(function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
});
}
}
Lastly, maybe you should tell the controller to be able to repond_to json:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
respond_to do |format|
format.html # The .html response
format.json { render :json => #user_time_checks }
end
end
end

Rendering JSON from AJAX call in Rails

I have an ajax call to fetch information from Flickr API which returns JSON data. I want to display values from JSON data in my view. I do this by editing some innerHTML with jQuery. The problem I am having is that the data is undefined, so it looks like a scoping problem.
photo.js
jQuery(function() {
$('#<%=p[:id]%>').click(function (e) {
//ajax call to fetch photo info
var fetch_id = '<%=p[:id]%>';
var fetch_secret = '<%=p[:secret]%>';
$.ajax({
type: 'GET',
url: '/photos/fetch_info',
dataType: 'json',
data: { 'id' : fetch_id, 'secret' : fetch_secret },
success: function(data){
console.log(data) //returns Object
console.log(data.title) //returns appropriate title
//edit innerHTML of basic_modal
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %></div><div id='photo_title'><%=data.title %></div>"
);
//load modal
$('.basic_modal').modal({
overlayClose:true
});
} //end success: function(result)
});
When I print data.title to console, I get the appropriate title. However, when I try to edit HTML and render <%=data.title %>, I get an undefined variable/method error.
Any tip on how I can display the data in my modal in the view?
Here is my controller:
def fetch_info
#info = flickr.photos.getInfo(:photo_id => params[:id], :secret=> params[:secret])
respond_to do |format|
format.json { render :json => #info }
end
end
var result = jQuery.parseJSON(data);
You donot need to do this, Because datatype:JSON already parse the data
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %>
</div><div id='photo_title'><%="+data.title+" %></div>"
);
this might help you

Resources