Coder Social home page Coder Social logo

pjax_rails's Introduction

PJAX for Rails

Build Status

Integrate Chris Wanstrath's PJAX into Rails via the asset pipeline.

To activate, add this to your app/assets/javascripts/application.js (or whatever bundle you use):

//=require jquery.pjax

Then choose all the types of links you want to exhibit PJAX:

// app/assets/javascripts/application.js
$(function() {
  $(document).pjax('a:not([data-remote]):not([data-behavior]):not([data-skip-pjax])', '[data-pjax-container]')
});

For this example, the PJAX container has to be marked with data-pjax-container attribute, so for example:

<body>
  <div>
    <!-- This will not be touched on PJAX updates -->
    <%= Time.now %>
  </div>

  <div data-pjax-container>
    <!-- PJAX updates will go here -->
    <%= content_tag :h3, 'My site' %>
    <%= link_to 'About me', about_me_path %>
    <!-- The following link will not be pjax'd -->
    <%= link_to 'Google', 'http://google.com', 'data-skip-pjax' => true %>
  </div>
</body>

Layouts

By default, the pjax_rails gem will not render your application layout file and will instead only return the yielded view. But if you have additional content you want to always be returned with your pjax requests, you can override pjax_layout in your controller and specify a layout to render (by default, it's false)

class ApplicationController < ActionController::Base
  def pjax_layout
    'pjax'
  end
end

pjax_rails's People

Contributors

alindeman avatar amatsuda avatar anatol avatar bkeepers avatar crackofdusk avatar dhh avatar fxn avatar ianterrell avatar jacobbednarz avatar jbampton avatar jeroenvisser101 avatar johncjensen avatar joliss avatar josh avatar koenpunt avatar ma2gedev avatar marcosmenegazzo avatar meesterdude avatar navied avatar oscardelben avatar rafaelfranca avatar route avatar theempty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pjax_rails's Issues

After update to 0.3.4 pjax was broken in half of app

Code in js like this doesn't work anymore.

$('.second_tabs a, .pjax_pages a').pjax('.box_info');
$('a[data-use-pjax]').pjax('.box_info');

But this one - works correct

$.pjax({
     url: $('.tabs_ajax a:first').attr('href'),
      '.box_info'
});

Updating multiple data areas on click

Hi, so basically, I have a sidebar and a content area. The sidebar sometimes changes depending on the content page it is on. What would be the best way to go about updating the sidebar when it's appropriate to do so?

Thanks a lot, and I apologize if this is the wrong place to put this. I wasn't sure where else.

Overriding the default trigger

Can I avoid having this run (without forking and using the forked version?)

$ -> $('a:not([data-remote]):not([data-behavior]):not([data-skip-pjax])').pjax('[data-pjax-container]')
eg: https://github.com/rails/pjax_rails/blob/master/lib/assets/javascripts/pjax/enable_pjax.js.coffee#L1

I'm a little green so the answer may be obvious, but in essence, I want to let pjax pick the container from the links data-pjax attribute, and not just use "data-pjax-container".

TIA,
Rasheed.

div#main

It updates the content only inside #main div, right? Is there any opportunity to specify another selector for that container?

Broken redirect after destroy.

Enabling pjax breaks redirect after destroy in Rails. For example, if object is destroyed from its 'show' page, redirect to 'index' page is not happens, and browser tries to fetch 'show' page again, raising exception.

I'm not sure if this is expected behaviour.

Rails 3.2.8, pjax_rails 0.3.3

Use request.fullpath instead of request.url in X-PJAX-URL header

Currently the code looks like below:

def set_pjax_url
  response.headers['X-PJAX-URL'] = request.url
end

For some reason, in my development env, I have to use a domain name, and I use nginx to forward the request to localhost:3000.

But X-PJAX-URL in each response begins with http://localhost:3000, which is not the same domain recognized by browser, and the browser stops execution at the following line in jquery.pjax:

window.history.replaceState(pjax.state, container.title, container.url)

Why not use request.fullpath instead of request.url to avoid host/port issues?

Release 0.5.0

Since the 0.4.0 release, pjax_rails has updated to pjax 1.9.6 and gained support for rails 5. I think it makes sense to release a new version.

However a new release is blocked by the following:

  • Decide which versions of rails to support. (The current Rails maintenance policy excludes versions before 4.2. Do we also remove support for them? Do we maintain backward compatibility?)
  • Fix the build accordingly. (The build is currently broken for various combinations of ruby implementation, ruby version and rails version.)

I am willing to help with fixing the build.

Feel free to add items I have forgotten.

PJax 1.0

Should be updated with latest.

Bump version?

Currently, the version of pjax_rails on rubygems is very outdated and doesn't work on ruby 1.8. Would it be possible to upgrade to the latest version on Github?

Don't PJAX links with targets or links with a protocol?

I don't know if it's possible. But that would be awesome. So then it would see http:// or https:// and decide that they must be another site and not use PJAX. Also if the target is set then it should just let the default action take place.

No X-PJAX in the headers

Hello,

I'm experiencing with Rails 3.1 and Pjax, I added a "data-remote"="true" to the links I want to test, and then in the controller that is receiving the request from such link, I checked for headers['X-PJAX'] to render no layout if it's found.. however it didn't not work..

Investigating the headers in Fireget, I see no X-PJAX at all, but I do see it on http://pjax.heroku.com

Leaving it as is with, the ajax request does happen but no content is changed, I added the data-pjax-container="true" to an

element

<header>
.....
<a href="/about" data-remote="true">About</a>
</header>

....


<article class='round' data-pjax-container='true' id='main'>
....
</article>

Is this an issue or have I done something wrong?

Called the page twice

I have a link and a container:

-# Link
= link_to 'Projects', projects_path

-# Contrainer
#main.container{ "data-pjax-container" => true }

When I click on it, it load the page twice. The first time with the X-PJAX = true but not the second time. (see attached).

Any idea ?

http://imgur.com/4Gfd2

Multiple containers

Any way to use multiple containers at the moment? If not this would be a nice addition

  <div data-pjax-container>
    <!-- PJAX updates will go here -->
  </div>

   <div data-pjax-container-2>
     <!-- PJAX updates will go here -->
   </div>

 redirect_pjax_to :show, @project (defailt goes to container)

 redirect_pjax_to :show, @project, :container => '2'

Fails with "RuntimeError: can't modify frozen string" when response received through redirection

So, I'm not entirely clear on how this is happening, but when I follow a redirect to my desired response, on the other end of the redirect request.env['QUERY_STRING'] is a frozen empty string.

I'm not sure who is supplying the string, but I'm fixing the bug with the following in my ApplicationController:

def strip_pjax_param
  if request.env['QUERY_STRING'].frozen?
    request.env['QUERY_STRING'] = request.env['QUERY_STRING'].dup
  end
  super
end

Can't load pjax

Setting //= require pjax in assets/javascripts/application.js.coffee, after put 'pjax-rails' in Gemfile then running bundle install:

Started GET "/assets/default/application.js" for 127.0.0.1 at 2011-05-19 05:41:26 -0300
[Sprockets] /default/application.js b49b6fd4af856dde889a3b8f7163df00 stale
[Sprockets] /default/application.js building

Sprockets::FileNotFound (couldn't find file 'pjax/index'):

Calls Action Twice

I cannot figure this out: a PJAX request generates two requests:

Started GET "/presentations/new?_pjax=true" for 127.0.0.1 at 2012-03-21 01:03:52 -0600
Processing by PresentationsController#new as HTML
  Parameters: {"_pjax"=>"true"}
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 83783472]]
  Rendered presentations/new.html.erb within layouts/presentations (4.0ms)
Completed 200 OK in 35ms (Views: 32.2ms | ActiveRecord: 0.4ms)


Started GET "/presentations/new" for 127.0.0.1 at 2012-03-21 01:03:52 -0600
Processing by PresentationsController#new as HTML
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 83783472]]
  Rendered presentations/new.html.erb within layouts/presentations (6.0ms)
Completed 200 OK in 32ms (Views: 28.9ms | ActiveRecord: 0.4ms)

And nothing is updated via Javascript โ€“ it just refreshes the whole page.

<section id="presentations">
  <ul>
    <li class="new">
      <%= link_to "Add", new_presentation_url %>
    </li>
  </ul>
</section>
<div data-pjax-container></div>

I've added #= require pjax to my assets file. Not sure what else to do?

Rails 3.2 pjax_rails jquery sizzle syntax error: unrecognized expression

I am applying pjax on a link which has the href /search?p=true&q=d&t=c/ . The pjax functionality works, but it always spits the:

Error: Syntax error, unrecognized expression: /search?p=true&q=d&t=p
[Break On This Error]   

throw new Error( "Syntax error, unrecognized expression: " + msg );

which when inspected comes from Sizzle's:

Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
}; 

when Jquery fires:

xhr.send( ( s.hasContent && s.data ) || null );

Rails: Initiating 2-3 simultaneous requests

I enabled this gem on the following link:

= link_to current_language, sites_language_url, data: { pjax: true, turbolinks: false }

Here is my pjax initialization:

document.addEventListener( 'turbolinks:load', function() {
    $(document).pjax( 'a[data-pjax]', '[data-pjax-container]' );
});

But as the logs show, a secend request has been made after clicking on the link, interrupting the pjax request. How can I fix this?

Started GET "/language?_pjax=%5Bdata-pjax-container%5D" for 127.0.0.1 at 2017-06-11 21:24:42 +0200
Processing by Sites::NavController#language as HTML
  Parameters: {"_pjax"=>"[data-pjax-container]", "subdomain"=>""}
  User Load (1.0ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 7417750677789892896 ORDER BY `users`.`id` ASC LIMIT 1
Started GET "/language" for 127.0.0.1 at 2017-06-11 21:24:42 +0200
  Rendering sites/nav/language.html.haml
  Rendered sites/nav/language.html.haml (2.0ms)
Completed 200 OK in 1013ms (Views: 619.2ms | ActiveRecord: 1.0ms)    

Processing by Sites::NavController#language as HTML
  Parameters: {"subdomain"=>""}
  User Load (0.0ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 7417750677789892896 ORDER BY `users`.`id` ASC LIMIT 1
  Rendering sites/nav/language.html.haml within layouts/application
  Rendered sites/nav/language.html.haml within layouts/application (3.0ms)
  Rendered shared/assets/icons/loaders/_saving.html (0.0ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (40.0ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (4.0ms) [cache miss]
  Rendered shared/layouts/body/notifications/_notifications.html.haml (112.1ms) [cache miss]
  Rendering layouts/base.html.haml
  Rendered shared/layouts/head/analytics/_google_analytics.html.erb (1.0ms) [cache miss]
  Rendered shared/layouts/head/_schema_markup.html (0.0ms) [cache miss]
  Rendered layouts/base.html.haml (1343.5ms)
Completed 200 OK in 1780ms (Views: 1739.7ms | ActiveRecord: 0.0ms)---

EDIT:

I just noticed that while in development every pjax request's behavior is like this, in production only the first request does not work. All following requests initiate as expected.


EDIT 2:

Now, I noticed that all of a sudden the site featuring the pjax-enabled link automatically makes a request to it when loading. I did change nothing, I am aware of. This leads to this request scheme after making one initial request:

Started GET "/login" for 127.0.0.1 at 2017-06-14 14:46:46 +0200
Processing by Devise::SessionsController#new as HTML
  Parameters: {"subdomain"=>""}
  Rendering devise/sessions/new.html.haml within layouts/application
  Rendered shared/assets/icons/brand/_logo.html.erb (0.5ms) [cache miss]
  Rendered shared/assets/icons/resources/apps/_google_white.html (1.0ms) [cache miss]
  Rendered shared/assets/icons/loaders/_button.html (1.2ms) [cache miss]
  Rendered shared/layouts/body/devise/_login.html.haml (477.5ms) [cache miss]
  Rendered shared/assets/icons/brand/icon/_icon_light.html (0.5ms) [cache miss]
  Rendered shared/layouts/body/_footer.html.haml (50.5ms) [cache miss]
  Rendered devise/sessions/new.html.haml within layouts/application (655.1ms)
  Rendered shared/assets/icons/loaders/_saving.html (0.0ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (42.2ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (4.0ms) [cache miss]
  Rendered shared/layouts/body/notifications/_notifications.html.haml (119.3ms) [cache miss]
  Rendering layouts/base.html.haml
  Rendered shared/layouts/head/analytics/_google_analytics.html.erb (0.9ms) [cache miss]
  Rendered shared/layouts/head/_schema_markup.html (0.0ms) [cache miss]
  Rendered layouts/base.html.haml (1422.0ms)
Completed 200 OK in 2740ms (Views: 2656.8ms | ActiveRecord: 5.9ms)


Started GET "/language?_pjax=%5Bdata-pjax-container%5D" for 127.0.0.1 at 2017-06-14 14:46:50 +0200
Processing by Sites::NavController#language as HTML
  Parameters: {"_pjax"=>"[data-pjax-container]", "subdomain"=>""}
Started GET "/language" for 127.0.0.1 at 2017-06-14 14:46:51 +0200
  Rendering sites/nav/language.html.haml within layouts/pjax
  Rendered sites/nav/language.html.haml within layouts/pjax (4.1ms)
Completed 200 OK in 1109ms (Views: 685.2ms | ActiveRecord: 0.0ms)


Processing by Sites::NavController#language as HTML
  Parameters: {"subdomain"=>""}
  Rendering sites/nav/language.html.haml within layouts/application
  Rendered sites/nav/language.html.haml within layouts/application (7.0ms)
  Rendered shared/assets/icons/loaders/_saving.html (1.0ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (42.1ms) [cache miss]
  Rendered shared/components/notifications/_notification.html.haml (4.0ms) [cache miss]
  Rendered shared/layouts/body/notifications/_notifications.html.haml (122.0ms) [cache miss]
  Rendering layouts/base.html.haml
  Rendered shared/layouts/head/analytics/_google_analytics.html.erb (0.0ms) [cache miss]
  Rendered shared/layouts/head/_schema_markup.html (1.0ms) [cache miss]
  Rendered layouts/base.html.haml (1451.0ms)
Completed 200 OK in 1920ms (Views: 1880.3ms | ActiveRecord: 0.0ms)

Weird https issue

Hi!
I installed this and it worked good on my dev, but ofc when i deployed it to production i stucked on https and http issue when clicking on a link:

Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://***.com/category' cannot be created in a document with origin 'https://***.com'.

The links are just /category and such, so i don't know it is trying to go to http://. Do you guys know?

Back Button does not work when response is 500 Server Error

Hi.

When using pjax_rails and the server responds with a 500 error (for example Action method not specified) the pjax javascript redirects the request and displays the error message as usual.

Unfortunately the back button does not work anymore. If you click back, the url changes correctly but the page content is not updated. This only happens in Chrome (21.0.1180.82) and Safari, in Firefox the back button works correctly for that cases.

On an error you use this

window.location.replace(container.url)

and I guess the browser is supposed to do a full page reload when you click on the back button after a window.location.replace() redirect ? Obviously this doesn't happen on Chrome/Safari.

Unfortunately I were not able to find a quick fix for this. Do you have an idea? Or is the right solution simply to change the 500.html's in production system etc. to include the full layout and javascript stack so that the back button should work again?

Application.js Example

Is this example really correct?

$('a:not([data-remote]):not([data-behavior]):not([data-skip-pjax])').pjax('[data-pjax-container]');

I couldn't get it to work and looking around, it appears that what is passed to the .pjax method should actually be the link targets -- not the container? Am I missing something?

$(container).pjax( link, options )

Thanks,
Tom

Explicit support for Rails 4

If Rails 4 is supported, it's not mentioned in the README.

It would seem that it is supported, based on DHH's recent blog post, but making that crystal clear would be helpful.

Google Tag Manager pushState/replaceState

On a regular page load, bothe pushState and replaceState are called, which causes duplicate page views in the Google Tag Manager for the event "History change".

Is this intentional? Or is there something I missed in the configuration?

JS not interpreted after redirect_pjax_to call

Hi,

I set up pjax_rails and it works great for action that don't use "redirect_pjax_to".
As your example, the following : "redirect_pjax_to :show, @project", does work but the render js: is not interpreted.

The content of the pjax div is filled with the raw js although the response header is set to "text/javascript".

I can't figure out why.

Failing tests for ~> 3.0

@rafaelfranca I've noticed that tests failed against ~> 3.0
The reason is that layout behavior has changed for ~> 4.0
For ~> 4.0 we rely on _layout method and then fallback do default layout findings, but for ~> 3.0 we look for a layout in file system and only then call super.
Below I provided a patch for 3-2-stable but apparently it's not back compatible. If we cannot merge this I suppose we have to emphasize it in README or any other ideas are welcome!

diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
index 3b07e4c..c52394c 100644
--- a/actionpack/lib/abstract_controller/layouts.rb
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -275,11 +275,8 @@ module AbstractController
         remove_possible_method(:_layout)

         prefixes    = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
-        name_clause = if name
-          <<-RUBY
-            lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super
-          RUBY
-        end
+        default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super"
+        name_clause = default_behavior if name

         if defined?(@_layout)
           layout_definition = case @_layout
@@ -305,28 +302,18 @@ module AbstractController
               name_clause
             end
         else
-          # Add a deprecation if the parent layout was explicitly set and the child
-          # still does a dynamic lookup. In next Rails release, we should @_layout
-          # to be inheritable so we can skip the child lookup if the parent explicitly
-          # set the layout.
-          parent   = self.superclass.instance_eval { @_layout if defined?(@_layout) }
+          parent = self.superclass.instance_eval { @_layout if defined?(@_layout) }
           @_layout = nil
-          inspect  = parent.is_a?(Proc) ? parent.inspect : parent

           layout_definition = if parent.nil?
-              name_clause
-            elsif name
-              <<-RUBY
-                if template = lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first
-                  ActiveSupport::Deprecation.warn 'Layout found at "#{_implied_layout_name}" for #{name} but parent controller ' \
-                    'set layout to #{inspect.inspect}. Please explicitly set your layout to "#{_implied_layout_name}" ' \
-                    'or set it to nil to force a dynamic lookup.'
-                  template
-                else
-                  super
-                end
-              RUBY
-            end
+            name_clause
+          elsif name
+            <<-RUBY
+              result = super
+              return #{default_behavior} if result.nil?
+              result
+            RUBY
+          end
         end

         self.class_eval <<-RUBY, __FILE__, __LINE__ + 1

layout is hardcoded to "application" for non-pjax requests

This will not work if you are using pjax_rails -- it will try to render the "application" layout instead of "my_layout":

class ApplicationController < ActionController::Base
  layout "my_layout"
end

This was what #23 was about; see the comments there.

Rails 5 support?

Do you have any plan to support Rails 5?
I'm pretty sure it should work with no changes (simply upgrading the gemspec)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.