Rails detect if request was AJAX

Rails detect if request was AJAX

Asked on January 11, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    AJAX request header[X-Requested-With] : 

    if request.xhr?
      # respond to Ajax request
    else
      # respond to normal request
    end
    

    Answered on January 11, 2019.
    Add Comment

    Using :remote => true in  links or forms, and respond_to block by calling request.xhr?.

    respond_to do |format|
       format.js { #Do some stuff }
    

    Answered on January 11, 2019.
    Add Comment

    Alternative solution for AJAX:

    request.xhr?
    

    Returns numeric or nil values not BOOLEAN values as  =~.

    irb(main):004:0> /hay/ =~ 'haystack'
    => 0
    irb(main):006:0> /stack/ =~ 'haystack'
    => 3
    irb(main):005:0> /asfd/ =~ 'haystack'
    => nil
    

    based on,

    # File actionpack/lib/action_dispatch/http/request.rb, line 220
    def xml_http_request?
      @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/
    end
    

    so,

    env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/ => 0
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.