jquery - Rails Respond with JSON to show Flashes in Ajax -
i have following code:
my jobs.html.erb
<div class="alert alert-error" style="display: none;"></div> <p><%= link_to t("jobs.index.buttons.similar_functions"), user_email_settings_path, :class => "nice medium blue button", :id => "saveagent" %> <small id="agent-saved" style="font-size: 1em !important;display: none;"><%= t("jobs.index.saved_agent") %></small><br /></p>
in page have following script:
$("#saveagent").on('click', function (event) { event.preventdefault(); $("#saveagent").addclass("disabled"); if( $("#saveagent").hasclass("disabled")) { $.ajax({ type: 'post', url: $(this).attr("href"), data: $("form").serialize(), complete: function() { $("#agent-saved").show(1).delay(20000).fadeout(800); $("#saveagent").removeclass("disabled"); alert("<%= flash[:error] %>"); $('div.alert').show(); $('div.alert').text("<%= flash[:error] %>"); } }); } });
the link_to goes to email-settings_controller.rb has following code:
def create api_params = params[:criteria] api_params = params[:criteria].reject{|k,v| v.to_s.blank?} @j = jobagent.new(name_for_job_agent(current_user), true, api_params) result = sap.submit_job_agent(@j.name, @j.to_xml, api_params_for_user) parser = messageparser.new(result.body["result"]) parser.messages.each |message| if message.type = "e" flash[:error] = "test" respond_to |format| format.json { render :json => flash} end end end end
now because it's ajax can't render flashes in normall way , have pass via json. code have seems works 50% of time returns correct "test" returns nothing.
is correct way of doing this? , how can work 100%.
thanks!
edit 1:
i'm trying following, found here : how send simple json response in rails?
def testme respond_to |format| msg = { :status => "ok", :message => "success!", :html => "<b>...</b>" } format.json { render :json => msg } # don't msg.to_json end end
but how read msg in complete function?
when use flash[:error] = '...'
, message consumed in next request, because syntax used before redirect_to
.
in case need message immediately, because you're using render
, should use instead:
flash.now[:error] = '...'
see how works: http://guides.rubyonrails.org/action_controller_overview.html#the-flash
Comments
Post a Comment