How can I stop the js response from being executed? - javascript

I am using Rails3.1 + Jquery. I have two forms that submit "update" requests to the same controller. For one, I would like to display an alert to the users to tell them whether the request was successful. The other should be quiet. My controller code looks like this:
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, :notice => 'Settings were successfully updated.' }
format.json { head :ok }
format.js { flash[:notice] = 'Settings were successfully updated.' }
...
The update.js is responsible for updating the flash div with the flash message. That works great. The problem is that this happens even from the form that I want to be silent. I'd like to modify the form itself to ignore any javascript in the response. I am having trouble finding anything in the Rails guides or through Google.

You can also solve this using js, set a variable called caller which holds the value of the calling form, after getting ajax response check if caller is form1 show message else return;
pseudo code:
var caller;
//In ajax response
if (caller==1) {
//show message
} else {
return;
}

Related

How to execute JS after redirect in a controller (Rails)?

Create
if #image.save
format.html { redirect_to vote_path(#image) }
format.js { render :js => "my_function();" }
end
so I'd like to fire up a function after the redirect has happened, but this doesn't work. Are there any other methods I could try and could you suggest me any please?
Thank you.
The redirect and render are separate. If you want it to run JS after the redirect, you can put some in the view that the vote_path is using. If you only want it to run after the redirect and not on the page load, you can set a flash before you redirect, and then check for the flash in the view.
An alternative would be to create a view to create.js.erb, and it run JS:
Your controller:
if #image.save
format.html { redirect_to vote_path(#image) }
format.js { }
end
create.js.erb
$("#share_window").show();

Rails Redirect Not Going as HTML

I have a sign up form that should redirect the user to their profile if sign up is successful. If registration fails I want to put up an error message without reloading the page using Javascript.
Here's my form header:
<%= form_for resource, as: resource_name, url: registration_path(resource_name), remote: true do |f| %>
My registration controller:
def create
respond_to do |format|
if resource.saved
sign_up(resource_name, resource)
format.html { redirect_to current_employer }
else
format.js { render 'employers/sign_up_failure' }
end
end
end
So the failure works. It displays an error message above the form without reloading the page.
The successful registration format.html { redirect_to current_employer } is not working.
My server log says the redirect was handled:
Redirected to http://localhost:3000/employers/27
But it looks like the show action on my Employers controller is being called as Javascript:
Processing by EmployersController#show as JS
So when I submit the form, it does not redirect me to my profile page. The page doesn't flicker. I am logged in though, so if I refresh the page it shows that I am logged in.
BTW, I am using Devise and my Registration controller is an amendment to what Devise uses.
Not sure why this isn't working. I've taken out the format.js {} part and it still sends the GET call to my Employers#Show action via JS. What I'd like is for the redirect to be formatted as HTML and take me to the profile page.
Any ideas?
SOLUTION
Thank you for you help. Face palm, I totally forgot about how remote: true works. Here is my implemented solution... hopefully someone finds this useful.
def create
respond_to do |format|
if resource.saved
sign_up(resource_name, resource)
#CHANGED
format.js { render js: "window.location.href = '/#{resource_name}s/#{resource.id}'" }
else
format.js { render "#{resource_name}s/sign_up_failure" }
end
end
end
This also improved the reusability of the code.
Because you have remote: true on the form it is submitted via ajax, you haven't said what to do if submitted via ajax and successful. The format requested is js not html which is why the redirect isn't working.
You'll need to create a create.js.erb file to serve if successful, handling the redirect through javascript with window.location = "wherever you want to go"

How can I redirect to a page after sending a JQuery get request in rails

I currently am trying to post a simple GET request from a search page and redirect to another page (a product page). However, when I send the request, nothing happens and the page does not change.
My code is below:
javascript
$('.imageBox').click(function () {
$.get("/s/product/ref", {
se: search,
pr: price,
crr: current,
bs: best,
bt: better,
gd: good
})
})
}
main_controller.rb
def product
respond_to do |format|
format.js { render :json => #json_data }
end
#search = params[:se]
end
I don't see code to direct the user to a different page. Try using window.location

Rails: How do load/trigger a js.erb using the controller?

I'm not even sure how to ask this question in a way thats understandable.
Basically, I'd like to do some javascript using a js.erb after I save. I'm submitting the form using a regular javascript/coffee-script file (if all fields are filled in correctly, then the form is submitted, else the form does nothing & just displays errors).
Part of my coffee-script:
fieldCorrectResponse: (fields, response) ->
if fields == correct
$('#new_mail')[0].submit()
else
$('#mail_error').text('error while filling out form')
my mail controller:
def create
#mail = Mail.new(mail_params)
if #mail.save
#PERFORM SOME JS USING A JS.ERB
else
render :new
end
END
So I guess what I'm really is asking is, how would you call a js.erb in the controller?
Wrote the solution to my problem below..
You should be able to render js and use create.js.erb.
Please try:
# MailsController
def create
#mail = Mail.new(mail_params)
if #mail.save
respond_to do |format|
format.js
end
else
render :new
end
END
Then, implement your javascript in app/views/mails/create.js.erb.
"do some javascript" isn't terribly descriptive. are you wanting to return a JSON object from the create action, which can then be parsed by the success callback on your jquery? Or do you want to have a template that has javascript in it that gets called as a result of the save action?
vinod covered the second way. make sure you have your routes set up correctly.
if you want to return a parseable JSON object, then write
render json: { some: 'json objects', should: 'go here' }
Also, not knowing what "mails" are, if you're trying to send emails that should be done with action mailer, and probably done as a part of committing the main model to the database (if you're creating a user and also trying to send an email, have a method as part of user creation that sends out the email).

how to have an application helper method work when the sent request is JS formatted?

I have a signed_in? method in rails that will drive u back to the landing page if you have been inactive for 5 minutes.
How do I make this work when the user clicks on a form submitted via js after the 5 minutes have passed? Obviously when this happens, the server sends the landing page back to the user, but it is not shown. Here is my signed_in method
def signed_in?
unless current_user
flash[:notice] = "Please log in"
redirect_to root_url
else
if session[:expiry_time].nil? || session[:expiry_time] < 5.minutes.ago
reset_session
flash[:notice] = "Please log in"
redirect_to root_url
else
session[:expiry_time] = 300.seconds.from_now
end
end
end
PS: I know it's horrible code, I'll be sure to refactor it :)
But I'd start by implementing an alternate redirect method that does a full redirect even for XHR requests:
def redirect_with_js location
if request.xhr?
# HTML response is expected:
render :text => "<script>document.location = '#{view_context.escape_javascript location}'</script>"
# JS response is expected:
# render :text => "document.location = '#{view_context.escape_javascript location}'"
else
redirect_to location
end
end
Then use this method when redirecting:
redirect_with_js boomeranked_url
The returned text depends on what type of response the AJAX request expects to get back (HTML or JS). I've included both versions. This should give you something to start with.
This is the solution I came up with it, I find it simpler. In the signed_in method:
respond_to do |format|
format.js {
flash[:notice] = "Please log in"
render 'home/not_logged_in'
}
And then on the not_logged_in view
window.location = '<%= root_url %>';

Categories

Resources