天道酬勤,学无止境

How to fail Ajax request in Rails?

When user clicks a specific item, I use jQuery's post method to update something in the database:

$.post("/posts/" + post_id + "/update_something", 
       { some_param: some_value }, 
       success_handler);

where update_something looks like this:

def update_something
  post = Post.find(params[:id])
  post.update_attributes(:some_field => params[:some_param])
  render :nothing => true
end

The problem is if update_attributes fails, the request still succeeds and success_handler is executed.

How could I cause the request to fail when update_attributes fails such that success_handler won't be executed?

评论

You can either do render :status => 400 (or some other error code) in Rails, which will trigger the error callback of $.ajax(), or you can render some JSON with an error message:

render :json => { :success => false }

Then in your success_handler function you would:

function success_handler (response) {
    if (response.success) {
        // do stuff
    }
}

Edit:

Oh, and update_attributes returns false when it fails. So you can render your response based on that.

Edit 2 years later:

After a couple years and seeing that this has a few upvotes, I'd highly recommend using the status: 400 method instead of rendering 200. It's what the error handler in AJAX requests are for, and should be used that way.

Well, you have to add an error handler, and give it an error to handle. So, in your JavaScript:

$.post( "/posts/" + post_id + "/update_something",
        { some_param : some_value }
      )
  .done( successHandler )
  .fail( errorHandler )      // define errorHandler somewhere, obviously
;

And in Rails:

def update_something
  post    = Post.find params[ :id ]

  success = post.update_attributes :some_field => params[ :some_param ]

  head success ? :ok : :internal_server_error
end

Note: 500 may or may not be the appropriate error code here—choose whichever among the 400s and 500s is appropriate.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • rails3 rails.js和jquery捕获ajax请求的成功和失败(rails3 rails.js and jquery catching success and failure of ajax requests)
    问题 以前,在Rails 2.3.8中,我使用了原型帮助器link_to_remote和form_remote_for (以及其他)。 这些具有:update选项,如下所示: link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } (文档中的示例)。 此示例在成功后将使用类“购物车”更新html元素,而在失败时将更新“错误”类。 现在,我相信操作方式已经改变,相反,我们这样写: link_to "Add to cart", :url => {:action => "add", :id => product.id}, :remote => true 并且没有设置:update选项了。 现在,代替普通的html,我们渲染javascript,如下所示(在jquery中): $('.cart').replaceWith(<%= escape_javascript(render :partial => 'cart') %>) 但是您如何处理错误情况? 我可以在控制器中处理它,并使用单独的视图吗? 以某种方式能够模仿我们以前的行为对我来说似乎很有用。 有任何想法吗? 回答1 哈!
  • Rails controller - execute action only if the a Rails UJS method inside succeed (mutually dependent methods)
    Following another question (Rails controller - execute action only if the two methods inside succeed (mutually dependent methods)), I would like to ensure that inside one of my controller's action, if the user does not see the message displayed by a Rails UJS method, then the first methods of the controller action are not implemented either. CONTEXT I have a Controller with a method called 'actions'. When the app goes inside the method 'example_action', it implements a first method (1) update_user_table and then (2) another update_userdeal_table. (both will read and write database) and then (3
  • 警告:无法验证CSRF令牌的真实性(WARNING: Can't verify CSRF token authenticity rails)
    问题 我正在使用AJAX将数据从视图发送到控制器,但出现此错误: 警告:无法验证CSRF令牌的真实性 我想我必须将此令牌与数据一起发送。 有谁知道我该怎么做? 编辑:我的解决方案 我通过将以下代码放入AJAX帖子中来完成此操作: headers: { 'X-Transaction': 'POST Example', 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }, 回答1 你应该做这个: 确保布局中有<%= csrf_meta_tag %> 将beforeSend添加到所有ajax请求中以设置标头,如下所示: $.ajax({ url: 'YOUR URL HERE', type: 'POST', beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, data: 'someData=' + someData, success: function(response) { $('#someDiv').html(response); } }); 要在所有请求中发送令牌,可以使用: $.ajaxSetup({ headers: { 'X-CSRF
  • Problem with jQuery.ajax with 'delete' method in ie
    I have a page where the user can edit various content using buttons and selects that trigger ajax calls. In particular, one action causes a url to be called remotely, with some data and a 'put' request, which (as i'm using a restful rails backend) triggers my update action. I also have a delete button which calls the same url but with a 'delete' request. The 'update' ajax call works in all browsers but the 'delete' one doesn't work in IE. I've got a vague memory of encountering something like this before...can anyone shed any light? here's my ajax calls: //update action - works in all browsers
  • How do I fetch the content for each tab using AJAX? Rails4, Bootstrap3
    I have 4 tab sections in an Event page view. I have it working where ALL the content for each tab is fetched and rendered when an Event page is requested. This doesn't seem like a good solution for scalability... How do I fetch the content for each tab using AJAX when a tab is clicked on? (First time doing it... looks simple in theory but failing to get it working) I tried adding remote: true to the tab links but that doesn't play well with the in-page references - it makes the same get request Events#Show for all the tabs which makes it difficult to determine which tab content is requested
  • jQuery.ajax在IE中带有“删除”方法的问题(Problem with jQuery.ajax with 'delete' method in ie)
    问题 我有一个页面,用户可以在其中使用按钮编辑各种内容,并选择触发ajax调用的页面。 特别是,一个操作导致一个带有一些数据和一个“ put”请求的远程调用url,(如我使用的是宁静的rails后端)触发了我的更新操作。 我还有一个删除按钮,该按钮调用相同的URL,但带有“删除”请求。 “更新” ajax调用在所有浏览器中都有效,但“删除”一个在IE中不起作用。 我之前碰到过类似这样的事情,记忆犹新……任何人都可以找到任何亮点吗? 这是我的ajax电话: //update action - works in all browsers jQuery.ajax({ async:true, data:data, dataType:'script', type:'put', url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId, success: function(msg){ initializeQuizQuestions(); setPublishButtonStatus(); } }); //delete action - fails in ie function deleteQuizQuestion(quizQuestionId, quizId){ //send ajax call to back end to change
  • Ember.js ember-data restadapter无法加载json(Ember.js ember-data restadapter fail to load json)
    问题 干杯! 我有余烬数据存储: TravelClient.Store = DS.Store.extend({ revision: 11, adapter: DS.RESTAdapter.create({ bulkCommit: false, url: "http://someIP:somePORT"}) }); 和路由器: TravelClient.ToursRoute = Ember.Route.extend({ model: function() { return TravelClient.Tour.find(); } }); 我从远程服务器收到此JSON: { "tours": [ { "id": "5110e8b5a8fefe71e0000197", "title": "qui deserunt dolores", "description": "Id velit nihil.", "seats": 12, "options": [ ], "images": [ { "id": "5110e8b5a8fefe71e0000196", "url": "url" } } 但是,当我尝试return TravelClient.Tour.find()它失败并显示: http://someIP:somePORT/tours 404 (Not Found)
  • Rails通过ajax提交表单并更新视图(Rails submitting a form through ajax and updating the view)
    问题 我想通过ajax更新表单提交而无需重新加载页面并根据它更新视图。 我尝试了不同的方法,但由于不熟悉Rails而失败了。 这是情况。 模态 def new @new_entry = current_user.notes.build @words = current_user.notes @notes_false_list = current_user.notes.where(known: false).order("title").group_by { |note| note.title[0] } @notes_true_list = current_user.notes.where(known: true).order("title").group_by { |note| note.title[0] } end 在查看表单代码。 <%= form_for @new_entry, :html => {:class => 'home-form without-entry clearfix'} do |f| %> <%= f.text_field :title, placeholder: 'Squirrel', autofocus: true, class: 'title-field pull-left' %> <%= f.submit '', class: 'btn home
  • rails - Choosing captcha plugin [closed]
    Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 7 years ago. Improve this question There are a lot of captchas plugins in Rails and also many types of solutions for preventing spamming and flooding. So it isn't only Rails question. Let's see what types of plugins do we have: 1. Classic image captcha (zendesk's Captcha, Simple_captcha, Validates_captcha, winton's Captcha, Raptcha). positive: Can be effective to prevent automatic decrypt
  • Rails,Devise身份验证,CSRF问题(Rails, Devise authentication, CSRF issue)
    问题 我正在使用Rails做一个单页应用程序。 登录和注销时,使用ajax调用Devise控制器。 我遇到的问题是,当我1)登录2)退出然后再次登录时不起作用。 我认为这与CSRF令牌有关,该令牌在我退出时会重置(尽管它不应该出现),并且由于它是单页,因此旧的CSRF令牌会在xhr请求中发送,从而重置会话。 更具体地说,这是工作流程: 登入登出登录(成功201。但是会打印WARNING: Can't verify CSRF token authenticity服务器日志中的WARNING: Can't verify CSRF token authenticity ) 后续ajax请求失败401未经授权刷新网站(此时,页面标题中的CSRF更改为其他内容) 我可以登录,它可以正常工作,直到我尝试退出并再次登录。 任何线索非常感谢! 让我知道是否可以添加更多详细信息。 回答1 Jimbo做得很出色,解释了您遇到的问题背后的“原因”。 您可以采用两种方法来解决此问题: (如Jimbo的建议)重写Devise :: SessionsController以返回新的csrf令牌: class SessionsController < Devise::SessionsController def destroy # Assumes only JSON requests signed_out =
  • How to use the jQuery AJAX request and the Ruby on Rails 'render' method togheter?
    I am using Ruby on Rails 3.0.7 and jQuery 1.6.1 and I would like to know how to handle response xhr, status and ex variables after an AJAX request. The AJAX request is: $jQuery.ajax({ type: "POST", url: "<request_to_the_controller_method>", // see the code below error: function(xhr, status, ex) { // handling with 'xhr', 'status' and 'ex' variables } success: function(jqXHR, status, ex) { // handling with 'xhr', 'status' and 'ex' variables } }); In the controller I have: respond_to do |format| format.js { render ... # here should be properly stated the Ruby on Rails 'render' method :status =>
  • Rails使用复选框和jQuery Ajax更改布尔值(Rails change boolean value with checkbox and jquery ajax)
    问题 我是Rails的新手,尝试通过复选框并使用jquery ajax更改布尔值: <%- @tasks.each do |task| %> <div class="task-wrapper"> <%= check_box_tag 'completed', task.id , task.completed, :class => "task-check" %> <%= content_tag :span, task.task %> <%= content_tag :span, task.deadline %> </div> <% end %> 和javascript: $(".task-check").bind('change', function(){ if (this.checked){ var bool = this.checked ? 1 : 0; $.ajax({ url: '/todos/toggle', type: 'POST', data: '{"task_id":"'+ this.value +'", "bool":"'+ bool +'"}' }); } else { alert("no"); } }); 然后控制器: def toggle(task_id, bool) @task = Todo.find_by_id(task_id) if @task !=
  • Rails:Rails中的POST 422(不可处理实体)? 由于路线还是控制器?(Rails: POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller?)
    问题 我正在尝试为我网站上的用户提供有关品牌名称推文的“积分”或“积分”。 我在适当的视图上有花哨的Twitter小部件... <p><a href="https://twitter.com/share" class="twitter-share-button" data-text="Check Out This Awesome Website Yay" data-via="BrandName" data-hashtags="ProductName">Tweet</a> <div id="credited"></div> <script>window.twttr = (function (d, s, id) { var t, js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src= "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } }); }
  • 了解Rails真实性令牌(Understanding the Rails Authenticity Token)
    问题 就像我现在有很多次一样,我遇到了一些有关Rails中真实性令牌的问题。 但是我真的不想仅仅解决这个问题然后继续。 我真的很想了解真实性令牌。 好吧,我的问题是,您是否有关于此主题的完整信息来源,或者您愿意花时间在此处进行详细说明? 回答1 发生什么了 当用户查看表单以创建,更新或销毁资源时,Rails应用程序将创建一个随机authenticity_token ,将该令牌存储在会话中,并将其放置在表单的隐藏字段中。 当用户提交表单时,Rails会寻找authenticity_token ,并将其与会话中存储的表单进行比较,如果匹配,则允许继续请求。 为什么会发生 由于真实性令牌存储在会话中,因此客户端无法知道其值。 这样可以防止人们在不查看该应用程序本身中的表单的情况下将表单提交到Rails应用程序。 想象一下,您正在使用服务A,登录到服务后一切正常。 现在,假设您去使用服务B,并且看到了自己喜欢的图片,然后按一下该图片以查看较大尺寸的图片。 现在,如果服务B上存在一些恶意代码,它可能会向服务A(您已登录)发送请求,并通过向http://serviceA.com/close_account发送请求来删除您的帐户。 这就是所谓的CSRF(跨站请求伪造)。 如果服务A使用的是真实性令牌,则此攻击向量将不再适用,因为来自服务B的请求将不包含正确的真实性令牌,并且将不允许继续。
  • How to respond to HTML requests made via AJAX in Rails
    I'm trying to write a Rails controller method that will respond to get requests made both "normally" (e.g. following a link) and via ajax. Normal Case: The controller should respond with fully decorated HTML using the layout. Ajax Case: The conroller should respond with the HTML snippet generated by the template (no layout) Here's the jQuery code, I've created to run on the client side to do the get request. jQuery.get("http://mydomain.com/some_controller/some_action", {}, function(data, textstatus) { jQuery("#target").html(data); }, "html"); What's the best way to handle this in Rails?
  • 试图弄清Ruby on Rails远程:真正的回调(Trying to figure out Ruby on Rails remote: true callbacks)
    问题 所以我一直在研究如何设置它们,最后我得到了这段代码。 <script> $('#reportform') .bind("ajax:success", function(data, status, xhr) { $('#reportalert').text('Done.'); }); .bind("ajax:error", function(xhr, status, error) { $('#reportalert').text('Failed.'); }); </script> <h2>Review Driver</h2> <p>Fill out your review of the driver</p> <div class="hero-unit form-signin" id="reportformdiv"> <%= form_for(@report, html: { id: "reportform" }, remote: true, update: { success: "response", failure: "error"} ) do |t| %> <p id="reportalert"></p> <%= t.text_field :plant_site, placeholder: "Plant Site" %> <%= t.text_field :route
  • Ruby on rails: How to send an AJAX request to rails controller from login popup along with user given credentials
    Also, how to use the values entered in the popup, in the javascript function: login_request() which is being called on click, which will send the AJAX request eventually. Note: The code snippet includes all the fields enclosed in the popup. <input class="csrf-token" type="hidden" name="authenticity_token" value=""> <div class="form-row clearfix"> <label class="lbl-fld">Email ID</label> <input type="email" name="user[email]" ng-model="loginForm.email" placeholder="me@example.com" ng-required="true"/> <!--<span class="valid-chk">--> <!--<i ng-class="{'false':'icon-close', 'true': 'icon-correct'}
  • 禁用JS / Ajax请求时的ActionController :: InvalidAuthenticityToken(ActionController::InvalidAuthenticityToken when disable JS/Ajax request)
    问题 我有两种形式,可以选择remote: true ; 一个发送Ajax请求以create动作,另一个发送Ajax请求以destroy动作。 启用JavaScript时,所有工作正常,但是如果我禁用JavaScript,然后单击,则会出现此错误: ActionController::InvalidAuthenticityToken PersonsController#create 为什么显示此错误,我该如何解决? 注意:我正在使用Rails 4 更新 当我使用不带选项remote: true的普通形式时,rails会自动为身份验证令牌插入一个隐藏字段,但是当我在表单中使用remote: true ,HTML代码中就没有这样的字段。 看起来,当有remote选项时,Rails会以不同方式处理身份验证令牌,那么如何在两种情况下都能使它工作? 回答1 奇怪的是,这种行为在rails 4中已更改。http://www.alfajango.com/blog/rails-4-whats-new/ 现在,除非您将其明确定义为表单的选项,否则Rails表单将不会在表单中呈现CSRF字段: <%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %> <% end %>
  • CORS-通过允许服务器上的原始不使用JSONP的跨域AJAX(CORS - Cross-Domain AJAX Without JSONP By Allowing Origin On Server)
    问题 我在同一台服务器上有两个单独的应用程序,其中一个EmberJS试图对后端API进行跨域调用。 我设置了后端API,以允许来自该特定来源的跨域请求。 但是,有没有一种方法可以避免在这样的设置中使用JSONP? $.ajax在跨域请求发送之前将其阻止。 如果不是,那么CORS的意义何在?我实现了哪个服务器端来接受来自JS前端源的请求? 编辑 AJAX请求: $.ajax({ url: "api.lvh.me:3000/accounts/login", data: cred, type: "POST", xhrFields: { withCredentials: true }, success: function(response){ alert('succeeded!'); console.log(response); alert(response); }, failure: function(message){ alert("failed"); console.log(message); alert(message); } }); 回答1 如果启用了CORS,则无需使用JSONP。 Access-Control-Allow-Origin: http://www.example.com 如果在响应中设置了此标头,则普通的XmlHttpRequest将能够像访问同一域一样访问响应。
  • How to save a raw_data photo using paperclip
    I'm using jpegcam to allow a user to take a webcam photo to set as their profile photo. This library ends up posting the raw data to the sever which I get in my rails controller like so: def ajax_photo_upload # Rails.logger.info request.raw_post @user = User.find(current_user.id) @user.picture = File.new(request.raw_post) This does not work and paperclip/rails fails when you try to save request.raw_post. Errno::ENOENT (No such file or directory - ????JFIF??? I've seen solutions that make a temporary file but I'd be curious to know if there is a way to get Paperclip to automatically save the