Giter VIP home page Giter VIP logo

jquery-pjax's Introduction

pjax = pushState + ajax

pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.

pjax works by fetching HTML from your server via ajax and replacing the content of a container element on your page with the loaded HTML. It then updates the current URL in the browser using pushState. This results in faster page navigation for two reasons:

  • No page resources (JS, CSS) get re-executed or re-applied;
  • If the server is configured for pjax, it can render only partial page contents and thus avoid the potentially costly full layout render.

Status of this project

jquery-pjax is largely unmaintained at this point. It might continue to receive important bug fixes, but its feature set is frozen and it's unlikely that it will get new features or enhancements.

Installation

pjax depends on jQuery 1.8 or higher.

npm

$ npm install jquery-pjax

standalone script

Download and include jquery.pjax.js in your web page:

curl -LO https://raw.github.com/defunkt/jquery-pjax/master/jquery.pjax.js

Usage

$.fn.pjax

The simplest and most common use of pjax looks like this:

$(document).pjax('a', '#pjax-container')

This will enable pjax on all links on the page and designate the container as #pjax-container.

If you are migrating an existing site, you probably don't want to enable pjax everywhere just yet. Instead of using a global selector like a, try annotating pjaxable links with data-pjax, then use 'a[data-pjax]' as your selector. Or, try this selector that matches any <a data-pjax href=> links inside a <div data-pjax> container:

$(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container')

Server-side configuration

Ideally, your server should detect pjax requests by looking at the special X-PJAX HTTP header, and render only the HTML meant to replace the contents of the container element (#pjax-container in our example) without the rest of the page layout. Here is an example of how this might be done in Ruby on Rails:

def index
  if request.headers['X-PJAX']
    render :layout => false
  end
end

If you'd like a more automatic solution than pjax for Rails check out Turbolinks.

Check if there is a pjax plugin for your favorite server framework.

Also check out RailsCasts #294: Playing with PJAX.

Arguments

The synopsis for the $.fn.pjax function is:

$(document).pjax(selector, [container], options)
  1. selector is a string to be used for click event delegation.
  2. container is a string selector that uniquely identifies the pjax container.
  3. options is an object with keys described below.
pjax options
key default description
timeout 650 ajax timeout in milliseconds after which a full refresh is forced
push true use pushState to add a browser history entry upon navigation
replace false replace URL without adding browser history entry
maxCacheLength 20 maximum cache size for previous container contents
version a string or function returning the current pjax version
scrollTo 0 vertical position to scroll to after navigation. To avoid changing scroll position, pass false.
type "GET" see $.ajax
dataType "html" see $.ajax
container CSS selector for the element where content should be replaced
url link.href a string or function that returns the URL for the ajax request
target link eventually the relatedTarget value for pjax events
fragment CSS selector for the fragment to extract from ajax response

You can change the defaults globally by writing to the $.pjax.defaults object:

$.pjax.defaults.timeout = 1200

$.pjax.click

This is a lower level function used by $.fn.pjax itself. It allows you to get a little more control over the pjax event handling.

This example uses the current click context to set an ancestor element as the container:

if ($.support.pjax) {
  $(document).on('click', 'a[data-pjax]', function(event) {
    var container = $(this).closest('[data-pjax-container]')
    var containerSelector = '#' + container.id
    $.pjax.click(event, {container: containerSelector})
  })
}

NOTE Use the explicit $.support.pjax guard. We aren't using $.fn.pjax so we should avoid binding this event handler unless the browser is actually going to use pjax.

$.pjax.submit

Submits a form via pjax.

$(document).on('submit', 'form[data-pjax]', function(event) {
  $.pjax.submit(event, '#pjax-container')
})

$.pjax.reload

Initiates a request for the current URL to the server using pjax mechanism and replaces the container with the response. Does not add a browser history entry.

$.pjax.reload('#pjax-container', options)

$.pjax

Manual pjax invocation. Used mainly when you want to start a pjax request in a handler that didn't originate from a click. If you can get access to a click event, consider $.pjax.click(event) instead.

function applyFilters() {
  var url = urlForFilters()
  $.pjax({url: url, container: '#pjax-container'})
}

Events

All pjax events except pjax:click & pjax:clicked are fired from the pjax container element.

event cancel arguments notes
event lifecycle upon following a pjaxed link
pjax:click ✔︎ options fires from a link that got activated; cancel to prevent pjax
pjax:beforeSend ✔︎ xhr, options can set XHR headers
pjax:start xhr, options
pjax:send xhr, options
pjax:clicked options fires after pjax has started from a link that got clicked
pjax:beforeReplace contents, options before replacing HTML with content loaded from the server
pjax:success data, status, xhr, options after replacing HTML content loaded from the server
pjax:timeout ✔︎ xhr, options fires after options.timeout; will hard refresh unless canceled
pjax:error ✔︎ xhr, textStatus, error, options on ajax error; will hard refresh unless canceled
pjax:complete xhr, textStatus, options always fires after ajax, regardless of result
pjax:end xhr, options
event lifecycle on browser Back/Forward navigation
pjax:popstate event direction property: "back"/"forward"
pjax:start null, options before replacing content
pjax:beforeReplace contents, options right before replacing HTML with content from cache
pjax:end null, options after replacing content

pjax:send & pjax:complete are a good pair of events to use if you are implementing a loading indicator. They'll only be triggered if an actual XHR request is made, not if the content is loaded from cache:

$(document).on('pjax:send', function() {
  $('#loading').show()
})
$(document).on('pjax:complete', function() {
  $('#loading').hide()
})

An example of canceling a pjax:timeout event would be to disable the fallback timeout behavior if a spinner is being shown:

$(document).on('pjax:timeout', function(event) {
  // Prevent default timeout redirection behavior
  event.preventDefault()
})

Advanced configuration

Reinitializing plugins/widget on new page content

The whole point of pjax is that it fetches and inserts new content without refreshing the page. However, other jQuery plugins or libraries that are set to react on page loaded event (such as DOMContentLoaded) will not pick up on these changes. Therefore, it's usually a good idea to configure these plugins to reinitialize in the scope of the updated page content. This can be done like so:

$(document).on('ready pjax:end', function(event) {
  $(event.target).initializeMyPlugin()
})

This will make $.fn.initializeMyPlugin() be called at the document level on normal page load, and on the container level after any pjax navigation (either after clicking on a link or going Back in the browser).

Response types that force a reload

By default, pjax will force a full reload of the page if it receives one of the following responses from the server:

  • Page content that includes <html> when fragment selector wasn't explicitly configured. Pjax presumes that the server's response hasn't been properly configured for pjax. If fragment pjax option is given, pjax will extract the content based on that selector.

  • Page content that is blank. Pjax assumes that the server is unable to deliver proper pjax contents.

  • HTTP response code that is 4xx or 5xx, indicating some server error.

Affecting the browser URL

If the server needs to affect the URL which will appear in the browser URL after pjax navigation (like HTTP redirects work for normal requests), it can set the X-PJAX-URL header:

def index
  request.headers['X-PJAX-URL'] = "http://example.com/hello"
end

Layout Reloading

Layouts can be forced to do a hard reload when assets or html changes.

First set the initial layout version in your header with a custom meta tag.

<meta http-equiv="x-pjax-version" content="v123">

Then from the server side, set the X-PJAX-Version header to the same.

if request.headers['X-PJAX']
  response.headers['X-PJAX-Version'] = "v123"
end

Deploying a deploy, bumping the version constant to force clients to do a full reload the next request getting the new layout and assets.

jquery-pjax's People

Contributors

0b10011 avatar alexhill avatar anttimattila avatar aroben avatar brianmario avatar chris123457 avatar defunkt avatar drock avatar eval avatar freman avatar halida avatar josh avatar kim3er avatar littke avatar loonkwil avatar mislav avatar nv avatar olemoign avatar oscardelben avatar pborreli avatar rf- avatar sakuro avatar samypesse avatar sbader avatar sj26 avatar spantaleev avatar squeedee avatar sshirokov avatar sstephenson avatar tdhooper 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  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

jquery-pjax's Issues

Global settings and handlers.

Options passed to $("a").pjax(...) aren't available on back buttons - maybe exposing a $.pjax.settings object like facebox does would do the trick. What do you think?

XSS DOM-based

The method success() in jquery.pjax.js sends unvalidated data to a web browser on line 167, which can result in the browser executing malicious code.

popstate should use the correct URL

The one we actually made a request to, not the one the user sees. There might some extra data in the query string to help make the request more pjaxy.

Back button to initial state fails in Safari

Using Safari 5.0.5 on Mac:

  • load http://pjax.heroku.com/ (check pjax if not already checked)
  • click one of the pages (works fine)
  • hit back button

What happens is that the URL in the address bar changes, but the page content stays the same. This seems to only apply to whatever the initial state is - moving back through other PJAX'd states appears to work fine.

Unsightly _pjax=true parameter in link URLs after pjaxing

Figured out the solution myself, but putting it here for googleability if someone else has the same problem.

We saw the following behavior: if I'm on page /a and click a pjax link to page /b, everything is fine. But when I click a link from there on to page C, the link will say /c?_pjax=true and that's the URL I will see after following it.

The issue is simply that since pjax adds the _pjax=true parameter in its Ajax request for reasons of browser caching, the links in your view may render with that parameter included, depending on how you generate their URLs.

What I did in Ruby on Rails was simply a params[:_pjax] = nil in the controller (a before filter might be appropriate) before rendering the view. Doesn't interfere with the caching but helps the links render without that parameter.

anyone able to get script tags in result page to run?

They seem to be removed by jquery for me. I'm also using a fragment from a full html page (page caching ftw) so perhaps that complication is also causing problems. I'll try to come up with a minimized example case.

browser doesn't recognize jQuery if click pjax-ified links too rapidly?

Has anyone noticed this? I've got pjax() working fine but sometimes it just fails. It seems like failure correlates with size of loaded content or frequency of clicking links or back button. By fails, i mean it does a full page load on the selected href rather than ajax loading. The console error says can't recognize jQuery object and it can happen in chrome or firefox.

thanks,
tim

Using original ajax options in popstate

On one of my pages, my pjax request sends a custom header. Eg:

var request = $.pjax({
  headers:    {'X-SL-CONTEXT': 'sort and filter'},
  url:        url,
  timeout:    0,
  container:  container,
  fragment:   container
});

In popstate events, that custom header should be sent. Unfortunately, it isn't.

One solution is to patch jquery-pjax so that it stores the headers object in the state object, and sends the headers in popstate events.

That feels like a lame solution, because other options might've been passed to the original $.pjax() call that should be included in popstate events, such as accepts, data, etc. Because of that, I feel like all of the options that are passed to $.pjax() that can be serialized should be stored in the state object.

What do you guys think?

X-PJAX is X-Pjax

Hey.

Both Chrome dev and Firefox 4.0 seem to be converting the name of the header to X-Pjax, so looking for X-PJAX serverside didn't work for me.

PJax a Form

Could this work?
jQuery('form[method=get]').pjax();

Of course this form has the data-pjax='' tag.

Please add the functionality if this is reasonable.
Thanks for all!

Handling of POST requests in unsupported browsers

The following two snippets have the same effect in unsupported browsers:

$.pjax({
  url: '/defunkt',
  type: 'POST',
  data: 'first_name=Chris',
  container: '#pjax'
})
window.location = '/defunkt'

That is to say, in unsupported browsers the POST data is not submitted (I found this somewhat surprising, as I think of $.pjax as a wrapper around $.ajax). There's an easy workaround:

$.ajax({
  url: '/defunkt',
  type: 'POST',
  data: 'first_name=Chris',
  success: function(html){ $('#pjax').html(html) }
})

Perhaps handing non-GET requests to $.ajax in unsupported browsers is a better fallback than setting window.location?

Client-side only implementation bugs

I struggled with why I couldn't get the simplest of test apps working with pjax. It was something like..

index.html

<html>
<head>
    <title></title>
    <script src="http://pjax.heroku.com/jquery.js"></script>
    <script src="http://pjax.heroku.com/jquery.pjax.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('a').pjax('#container', {
                fragment: '#container',
            })
        });
    </script>
</head>
<body>
    <a href="page.html">PJAX!</a>
    <div id="container">
        Replace this..
    </div>
</body>
</html>

page.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div id="container">
        <h1>Heading!</h1>
        With this..
    </div>
</body>
</html>

Issue 1

The issue turned out to be that pjax does a .find() on the ajax response. There are two issues with this:

  1. The elements jquery applies the .find() to might vary per browser: http://api.jquery.com/jQuery/#creating-new-elements
  2. .find() searches the descendants of each element in a set (http://api.jquery.com/find/)

In my case #container was in the matched set. Wrapping the #container div in another div fixed this issue.

Issue 2

The second problem I had was with the text inside of the remote #container div did not get transferred into the current pages #container div.

I solved this issue by changing.. data = $fragment.children(); to.. data = $fragment.contents(); in jquery.plax.js

Summary

  1. Make sure your fragment element is not the first element in the body
  2. DOM elements with nodeType #text will not be copied over unless wrapped in some other element

I hope to submit a pull request if I can think of a simple way to .find() on the selection, and its children.

Dysqus comments

Hello,

I am using PJAX for filling a container with a page that contains dysqus comments.

When the page is loaded as a full request the dysqus comments are rendered.

But when the request is made by PJAX the dyscus comments are not shown. I think the javascript code is not being executed.

Any ideas?

Problems with 'fragment' option

The current version of jquery.pjax.js isn't working for me on a client side setup by using the 'fragment' option:
$("a.pjax").pjax({container:"#maincontent",fragment:"#maincontent"});
After clicking an appropriate link I get a blank page and a couple of network errors (404). After removing the fragment option the target page will be loaded completly, without a pjax-call.
I'm wondering which pull request merge/update caused this issue, since I've downloaded the jquery.pjax.js which is still working for me just two month ago.

Is this spiderable?

My one concern with this is will it be spiderable by Google, etc since the content is loaded via jquery?

Problems with Safari's Reader

I don't where to file this issue, but it appears that Safari's Reader doesn't follow pjaxed links and always opens the last fully refreshed page.

Delay pjax after click

I'm trying to delay pjax from loading the next page until after my fadeout is complete, however pjax ignores the delay.

<script type="text/javascript">
    $(document).ready(function() {

        $('a.pjax').click(function() {
            $('#container').fadeOut(1000, function() {
               console.log('YOYOYO');
            });
        }).delay(1000).pjax({
            container: '#container',
            fragment: '#container'
        });
        $('#container').bind('end.pjax', function() {
            $('#container').fadeIn(1000) 
        });
    });
</script>

Browser shows partial page when I backed from outer domain

Hi,
I found a weird behavior.

Accessing pjax.heroku.com (pjax enabled) -> /dinosaurs.html -> github.com/defunkt/jquery-pjax, then back to /dinosaurs.html, I couldn't see whole dinosaurs page.
That is, browser shows partial page (which is the response of pjax request).

My environment is:
Google Chrome 10.0.648.204 and Firefox 4.0 on MacOSX 10.6.7 doesn't work as I expected.
Safari 5.0.4 on MacOSX 10.6.7 does work as I expected.

I think it may be a bug or an issue around Chrome and Firefox, but I'm not sure.

Excuse me if this behavior is a known issue.

Regards,

Safari spinning wheel never stops after reload

It looks like Safari spinning wheel never stops after reloading a page that used pjax and then navigating back to the page that called pjax. You can see it live at the demo page.

  1. Visit the demo: http://pjax.heroku.com/

  2. Click on dinosaurs or aliens

  3. Reload: Command + R

  4. Back: Command + [

  5. Safari spinning wheel never ends

Safari version: 5.1
OS: 10.6.8

Allow effects

Hello,
I think it would be really great if it was possible to use effects, for example to show the new content.

On redirect pjax updates the wrong url

On redirects with HTTP 301, pjax loads the right page, but updates to the wrong (requested) url while it should update to the page the redirect was to.

One way in which $.pjax doesn't mimic $.ajax?

Hi all, i'd like to call $.pjax inside a click(function(){}) such that I can use $(this) to get the attributes of a selected pjax-ified link. The goal is to send POST data specific to which link was clicked.

Here's some example code:

*div id="main></div*
*a class="each_link" title="title_1">link_1</a*
*a class="each_link" title="title_2">link_2</a*

$('a.each_link').live('click', function(){ 
var title=$(this).attr('title');
$.pjax({url: '/link' , type: 'POST', data: 'posted_data='+title+'' }); 

i'd like to be able to send "title_1" or "title_2" along as data but clicking either of these links kills my browser (chrome or firefox).

Can anyone advise on whether this is a $.pjax specific quirk?

thanks,
tim

URL incorrect on iOS

When following pjax-ified links on an iPhone or iPad, the URL does not match the current page.

The first link clicked updates the URL appropriately, but subsequent clicks are one behind the currently loaded content.

Please see this screenshot to see an example. The page title and content are correct, but the URL is not.

When refreshing the page, the URL changes to the correct URL and the proper page is reloaded.

Sinatra app

I am using Sinatra and want to use Pjax but for some reason that I don't understand it is not working.

App:

get '/docs/*' do                                           
  if request.xhr?
    puts "Sending a pjax request"  
    puts "docs/#{params[:splat].join('/')}.html"
    haml :"docs/#{params[:splat].join('/')}.html", :layout => false
  else
    haml :"docs/#{params[:splat].join('/')}.html", :layout => :'docs_layout'
  end  
end      

Log:

Sending a pjax request
docs/introduction.html
127.0.0.1 - - [29/Jun/2011 19:37:24] "GET /docs/introduction?_pjax=true HTTP/1.1" 200 1636 0.2096
[2011-06-29 19:37:24] ERROR Errno::ECONNRESET: Connection reset by peer
    /Users/Nerian/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `eof?'
    /Users/Nerian/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `run'
    /Users/Nerian/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
127.0.0.1 - - [29/Jun/2011 19:37:25] "GET /docs/introduction HTTP/1.1" 200 11345 0.1347

Javascript:

$(function() {  
    $('#index a').pjax('#doc')   
});                 

HTML

http://pastebin.com/uVXmBzL1

It seems that an ajax request is made but then something goes wrong and a non-ajax request is made, reloading the entire page. I am not sure where is the error.

I did a:

wget --header="X-Requested-With: XMLHttpRequest" http://localhost:3000/docs/validation?_pjax=true

And it gave me the right page, without layout. Maybe the problem is in the client side? But then, why the

ERROR Errno::ECONNRESET

In the server log?

I hope you can point me in the right direction :)
Thanks

Changing timeout default

Hello,

If I set $.pjax.defaults.timeout = 3000; (example) before set the Pjax for links, will it work?

Like:

    $.pjax.defaults.timeout = 3000;
    $('a.pjax').pjax('#container');

If not, could be added this option?

Thx!

Doesn't work well with noConflicts

The code works almost completely when jQuery noConflicts mode is on, however, one small line seems to break, and this breaks popState functionality, meaning no back button.

Changing line 166 from $ to jQuery fixes everything.

requests aborted

I am often getting requests aborted in Firefox and Google Chrome.
I tried to debug this and found this piece of code

    if ( xhr && xhr.readyState < 4) {
        xhr.onreadystatechange = $.noop
        xhr.abort()
    }

which makes perfectly sense but the requested aborted problem occurs also if there isn't another request pending.
I verified this with this code

    if ( xhr && xhr.readyState < 4) {
        alert('already pjaxing...');
    }

The popup isn't shown but the request often gets aborted. Server side everything works fine.
Any idea about this behaviour?

Loading a whole page

I've been trying to get pjax to work on my development site but I just can't get it to work.
Everytime I clicked on a link, I can see in the firebug console that it's trying to load the page but before the request is completed, I got navigated away to that page instead of loading the content through AJAX.

Add A Before Render Event

I was looking at how to populate multiple areas using pjax and noticed this post where you say you dont want to over complicate pjax.

#7

I think it would be beneficial to have an event that could be triggered just before pjax updates the container. This would allow users to do any pre-processing of data they needed (probably not a requirement but could be useful to some) and importantly would allow users to update multiple places.

From what i have created its a very simple change and uses the event system already being used.

My current implementation only updates the container if the beforeRender callback returns true, although this could be changed to return the content if the pre-processing feature mentioned above might be of use.

If your interested i can tidy up the code a bit more and do some more testing.

Doesn't Halt Loads?

If the example is any indication, it appears that clicking another PJAX link won't do anything while there is a request loading.

This is very unlike how the browser works. In this case, PJAX should stop the prior request and issue a new one.

pjax:cancel or 'result' property of pjax:end event needed

Currently a canceled pjax request will also trigger pjax:end event while the 'result' property of the event keeps undefined , which left no way to make out whether the request is finished or canceled.

So maybe 2 solutions:

  1. Add a pjax:cancel event instead pjax:end for canceled pjax request.
  2. Fulfil the 'result' property of the pjax:end event. There IS such a property now but it's always 'undefined'.

Callbacks don't persist after navigating away from a page

As I wrote in #25:

There's a problem with callbacks in pjax, however: they don't get run when returning to a pjax'd page after navigating away.

For example:

$('a').pjax('#main', { success: function(){
  console.log('pjax!')
}})

This code will log "pjax!" until you navigate away from the page. Once you return (via the back button) from navigating away, nothing will be printed. We can't persist callbacks with the History API.

This is a problem for the existing success, error, and complete user defined callbacks.

Instead, people should use the start.pjax and end.pjax events. We should probably not let anyone use anything else and add more pjax-specific events to make up for it.

Unfortunately, it's not that simple. Take the above example. If multiple pjax handlers are using #main, how can you tell if the end.pjax event fired is the one you anticipated?

Readme should be .md

Would be more readable. Awesome ASCII art should still work as it's properly 'nested'. Thanks! :-D

Demo page doesn't work

http://pjax.heroku.com/ is not working on both Safari and Chrome, didn't try Firefox but I guess that is the same.
The time stamp change every time I change click on a link.

[ EDIT ] Works on firefox 8.0.1 on OSX 10.6.8

HTTP_X_PJAX not always sent

HTTP_X_PJAX is not sent correctly unless / or file extension is added to the URL.

This do not send the header: < a href="/contact" >contact< /a >
These ones do: < a href="/contact/" >contact< /a > < a href="/contact.html">contact< /a >

Can't go back to a URL with a hash

Lets say I'm on the following page:

http://localhost/exchange#log

The hash selects a jquery tab by default.

I have an edit button on this page which loads my content into the container, works so far. Now If I press the back button pjax doesn't load the content until it hits a URL without a hash. So it has no trouble going back to http://localhost/exchange but can't go back to the URL I provided.

Alternate strategy to account for menus or other items

The current approach solves the problem:

I want to replace the content of an element with a new element from a url on the server.

But there are often other things which will need to be changed when this happens. A simple example is menus. If you have a hierarchical menu (the hierarchy of which is only known to the server-side application) and you want to represent the new active menu hierarchy (update the classes of links in some element), this approach can't work unless you PJAX an element from quite a bit higher in the DOM, which will reduce the utility.

I suggest that instead of setting what element gets replaced on the client side, and replacing that element with the entire response, we simply specify a URL, and allow the server side code to send back several elements, then replace those in the active page based on matching ids.

This would solve the menu example, but also any number of potential others, such as allowing for updates to an user alert box.

XSS via DOM

The method success() in jquery.pjax.js sends unvalidated data to a web browser on line 160, which can result in the browser executing malicious code.

In jquery-pjax.js, line 160, the success method doesn't properly validate the malicious input returned from making the hash. Mind you, it is only as strong as the client protections enabled on the browser.

one at a time

@brianmario says:

keep track of the last xhr request, when another one is attempted abort the last if its readyState is < 4

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.