简体   繁体   中英

Rails Respond with JSON to show Flashes in Ajax

I have the 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 that page I have the 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 to my email-settings_controller.rb who has the 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 do |message|
      if message.type = "E"
        flash[:error] = "test"
        respond_to do |format|
          format.json { render :json => flash}
        end
      end
    end
  end

Now because it's ajax I can't render my flashes in the normall way and I have to pass something via JSON. The code I have seems to works 50% of the time sometimes he returns the correct "test" sometimes he returns nothing.

Is this the correct way of doing this? And how can I get it to work 100%.

Thanks!

EDIT 1:

I'm trying the following, found here : How to send simple json response in Rails?

def testme
  respond_to do |format|
    msg = { :status => "ok", :message => "Success!", :html => "<b>...</b>" }
    format.json  { render :json => msg } # don't do msg.to_json
  end
end

But how do I read msg in my complete function?

When you use flash[:error] = '...' , the message will be consumed in the next request, because this syntax is usually used before a redirect_to .

In your case you need the message immediately, because you're using render , so you should use instead:

flash.now[:error] = '...'

See how it works: http://guides.rubyonrails.org/action_controller_overview.html#the-flash

I've fixed it like this changed my controller to this:

  respond_to do |format|
    format.json  { render :json =>{ :message => "Hello world"} }
  end

And changed my script to:

  $("#saveAgent").on('click', function (event) {
    event.preventDefault();
    $("#saveAgent").addClass("disabled");
    if( $("#saveAgent").hasClass("disabled")) {
          $.ajax({
            type: 'POST',
            url: $(this).attr("href"),
            data: $("form").serialize(),
            success: function(data) {
              $("#agent-saved").show(1).delay(20000).fadeOut(800);
              $("#saveAgent").removeClass("disabled");

              if (data.message != "") {
                $('.alert.alert-error').show();
                $('.alert.alert-error').text(data.message);
              }
            }
          });
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM