Coder Social home page Coder Social logo

bigskysoftware / intercooler-js Goto Github PK

View Code? Open in Web Editor NEW
4.7K 115.0 233.0 6.25 MB

Making AJAX as easy as anchor tags

Home Page: http://intercoolerjs.org

License: MIT License

JavaScript 30.18% Ruby 0.04% HTML 69.70% CSS 0.08%
html javascript jquery web-app front-end

intercooler-js's Introduction

htmx

intercooler 2.0 (renamed to htmx 1.0) has been released. It is smaller, more expressive and no longer has a dependency on jQuery.

You can view the new website here:

http://htmx.org

And the new repo here:

https://github.com/bigskysoftware/htmx


Introduction

Intercooler is a small (6.74KB gzipped) jQuery or zepto.js based library that allows you to add AJAX to your application using HTML attributes.

Here is an example:

    <!-- When this button is clicked an AJAX POST request is sent to /example and the 
         response content is swapped in to the body of the button -->
    <button ic-post-to="/example">
        Click Me!
    </button>

Despite this simplicity, intercooler supports quite a bit of functionality:

These features allow you to build modern web applications with little fuss, using a simple and intuitive REST-ful architecture that ensures good performance, excellent user experience and a minimum of complexity.

It also is very easy to incrementally retrofit intercooler into existing web applications to add AJAX functionality where it is most valuable.

Full documentation is available on the main intercooler website

Installing

Intercooler can be downloaded or hot-linked from the downloads page.

Or installed via bower:

     "dependencies": {
        "intercooler-js" : "1.2.0"
      }

Intercooler depends on jQuery v1.10.0 or higher.

License

Intercooler is licenced under the MIT License

Official Theme Music

Rober Parker

Contributing

To contribute a change to intercooler:

  • Fork the main intercooler repository
  • Create a new feature branch based on the development branch with a reasonably descriptive name (e.g. fix_http_get_parameter_overriding)
  • Implement your fix
  • Add a test to /test/unit_tests.html. (It's pretty easy!)
  • Create a pull request for that branch against development in the main repository

Thank you to all the contributors!

๐Ÿ•Š๏ธ๐Ÿ•Š๏ธ๐Ÿ•Š๏ธ

intercooler-js's People

Contributors

1cg avatar adamstep avatar alex-sichkar avatar allain avatar ammsa avatar artjomsimon avatar baumann74 avatar brejoc avatar cortesi avatar dbpreston avatar dependabot[bot] avatar evilotto avatar jsampson avatar jsampson2 avatar juggy avatar mdpaquin avatar niv avatar nnmer avatar overminddl1 avatar pableu avatar peterdavehello avatar pocketarc avatar radarhere avatar rgroli avatar schpet avatar scsmash3r avatar timb07 avatar tipsy avatar torohill avatar waldyrious 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

intercooler-js's Issues

Pass along CSRF tokens // Access $.ajaxSetup()

Hi.

I do something like this to send along a CSRF token on every request.

var csrftoken = $('meta[name=csrf-token]').attr('content');
  $.ajaxSetup({
      beforeSend: function(xhr, settings) {
          if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken)
          }
      }
  })

This basically allows me to make sure everything is okay, but I am having some trouble getting Intercooler to play along with this.

I've seen there is a _remote that is set to $ (jQuery), and I tried accessing that, but no luck so far, javascript is not my area of expertise.

What would be the best way of doing this? Preferably setting ajaxSetup options like this should be available in some easy way, since I will not be the only person wanting something like this :-)

By the way, excellent work on taking the tedious jQuery gritty work out of for example dynamically loading things and similar. I've been doing it by hand with jQuery and the amount of boilerplate code repeating ends up being tedious. ๐Ÿ‘

Jquery closest/find selector support

sometimes in list items it is helpful to have a descentant class selector for target instead of id , something like ic-target ="find .description"

Invalid HTML

ic-* attributes are not valid HTML.
Would it be possible to prefix them with data-?

Add ic-with-response for JSON handling/filtering/etc.

From the mailing list:

For JSON support, what if I added an attribute like ic-with-response that let you put add an arbitrary JS expression in to work with the server response? I could set it up so that you could use it to process JSON (as in your example) or do client-side processing or whatever.

Something like:

<a ic-post-to=โ€œ/my_apiโ€ ic-with-response=โ€œmyVar.handleResponse(response)โ€>Do It</a>

for JSON and then

<a ic-post-to=โ€œ/my_apiโ€ ic-with-response=โ€œreturn filterResponseOnClientSide(response)โ€>Do It</a>

to do a client-side filter.

Add 'ic-on' or 'ic-post-on' similar to 'ic-load-on' to do actions based on events.

I was just thinking perhaps it would be nice to have a attribute that would fire whatever event.

Example:

<form ic-post-to="/comments/new" ic-post-on="submit">
<textarea name="body" placeholder="Your comment" required="required" rows="2"></textarea>
</form>

Something like the above, or just a general ic-on="submit" that would work with all the different attributes (ic-post-to, ic-get-from and so on).

I thought of this because I want to submit a form using Intercooler when I press the enter key.
This may be possible already, let me know, in any case I think this could be a cool and useful mechanic.

ic-prompt triggers ajax request even if canceled

Given:

<button class="btn" ic-put-to="/action" ic-prompt="Enter Customer Id">Explain</button>

User clicks button Explain. Alert dialog of "Enter Customer Id" is displayed. User presses cancel.

Expected: noop

Actual: request is sent to server with null ic-prompt-value header.

in this case the complete event is not triggered when the defaultTransition is none

I noticed that the complete event is not triggering when the the defaulttransition is set to "none" and the reponse from the server contains the triggering element itself again.

HTML
 <div id="selftarget">
   <a ic-target="#selftarget" ic-get-from="/api">click me! (self targeted)</a>
</div>
<a ic-target="#externaltarget" ic-get-from="/api">click me! (external target)</a>
  <div id="externaltarget"></div>
JS
    $(function(){
      Intercooler.defaultTransition("none");

      $.mockjax({
        url: "/api",
        responseText: '<a ic-target="#selftarget" ic-get-from="/api">click again</a>'
      });

      $(document).on('beforeSend.ic', function(){
        alert('beforeSend')
      }).on('complete.ic', function(){
        alert('complete')
      });
    })

Whithout setting the defaultTransition to none all events are triggered as expected. "beforeSend" is always triggered.

Form validation

I'm not able to use IC with form validation in the proper way.
I tried 2 approaches.

Validation function that returns false if not valid, as I read here https://groups.google.com/d/msg/intercooler-js/EINwxcOO2h8/q00B3p8_jrAJ

The problem here is that the request is sent even if myValidation returns false

<form ic-post-to="/my/url" ic-on-beforeSend="myValidation()">
  <button>Submit</button>
</form>
function myValidation() {
   return false;
}
Another way I tried to validate the form.

Here the idea is to block the current request if the form is not valid and sent another req once it is valid.

I'm able to block the request the first time, but then, when my fake form become valid, I cannot send it.

<form ic-post-to="/my/url" ic-on-beforeSend="myValidation(xhr)">
  <button>Submit</button>
</form>
valid = false;
function myValidation(xhr) {
  if(! valid){//the first time is invalid
    xhr.abort();
    valid = true;//from the second time is valid
  }
}

Can you give me any advice about this?
Thanks

Detect AJAX failure and use addURLHandler() for fallback mode

Hello,
I am learning how to use intercooler.js and i would like to use it for some small / simple mobile HTML5 applications.
I would like to know if you plan to include something to detect when AJAX request failed and then use addURLHandler() for a fallback mode ?

New event indicating the end of a transition

The event "complete.ic" fires before the actual transition ends. Sometimes it is required to execute a callback to initialize parts of the ui which were just fetched. Sometimes the initialization requires the fetched ui to be visible. "complete-ic" fires when the transition might not be finished and the ui is still invisible or in the process of fading in.

Could "complete.ic" be fired after the transition?
Or could there be a new event introduced indicating the end of the transition?

ic-get-from not working when using target element

This does not work (the ictarget node remains unchanged when the a is clicked):

 <a ic-get-from="/myapp/test1" ic-target="#ictarget" ic-push-url="true">Click me!</a>
 <div id="ictarget"></div>

But this does:

<a ic-post-to="/myapp/test1" ic-target="#ictarget" ic-push-url="true">Click me!</a>

<div id="ictarget"></div>

What am I doing wrong?

Use HTTP Headers for Content Negotiation

It'd be nice if, instead of an HTTP parameter, we used the Accept header (or something similar) to denote that the client is expecting a partial HTML view.

For example, requests might be sent with the following header: Accept: text/html-partial, */*; q=0.01

This way, the same URI can be used to respond to various types of requests for the same resource:

app.get('/playlists', function(req, res, next) {
  var playlists = []; // real data might be here

  res.format({
    json: function() {
      res.send(playlists); // send a JSON object
    },
    html: function() {
      res.render('playlists', {
        playlists: playlists // render a full HTML page
      });
    },
    partial: function() {
      res.render('playlists', {
          layout: false
        , playlists: playlists // render only the partial HTML
      });
    }
  });
});

HTTPS failure CDN Hosted javascript

Tested site with SSL with script linked as "//cdn.intercoolerjs.org/intercooler-0.4.10.min.js" and this file failed to load. Apparently this particular CDN may not support https for this file.

Give a onpopstate event handler

When using Intercooler the window.onpopstate event is overwritten. How could I get a callback when user clicks the go back button in browser?

Dual ampersands in query string

I noticed that in at least one place there are 2 ampersands ('&'), e.g.: ic-request=true&hidden=hidden+value&email=&password=&ic-id=7&ic-last-refresh=1426609883108&ic-fingerprint=-1236882890&ic-current-url=%2Fdocs.html&&_method=POST

Notice the &&_method=POST at the end.

Allow client-side event to trigger dependency change

Intercooler dependency graph is nice. Could an enhancement be made that allow client side events to cause intercooler dependency graph to be triggered?

For example, imagine that I have a block of code defined like this:

<div IC-SRC='/some/url'> ajax content here... </div>
<button IC-MOCK-POST-TO:/some/url> click me </button>

When the button is clicked, an actual AJAX post doesn't occur, but the intercooler dependency graph is triggered as if had occurred. Doing this would let simple UI constructs to trigger updates as well as AJAX driven events.

Expose processHeaders()

We currently have the case where we have another JS component on the page (a modal overlay) which integrates its own xhr logic for loading content.

We would like to process the xhr response with intercooler in order to have a common API (the intercooler response header) for the backend to talk with the frontend.

Therefore it would be helpful if the function processHeaders() could be included into the public Intercooler JS API. At the moment I don't see way get access to this functionality inside Intercooler.

Triggers not working after cloning an element

I have a menu that I am cloning for mobile purposes. The menu at load time works great with intercooler, but when cloning the menu and adding it to the DOM, intercooler doesn't seem to react to the clicks. Does intercooler need to be reinitialized? Or does it not support this capability?

Double <script> call during update

I discovered that during execution of the "processICResponse", the content of the element being updated is set twice. This makes everything inside the <script> tag executed twice as well.

This is called first:

var dummy = $("<div></div>").html(newContent);  #line 753

and then this (https://github.com/LeadDyno/intercooler-js/blob/master/src/intercooler.js#L60):

transition.newContent(target, newContent, false, function () {  #line 757
    ....
        newContent : function(parent, newContent, isReverse, after){  #line 58
               parent.fadeOut('fast', function(){  #line 59
               ---> parent.html(newContent);  #line 60

InterCooler vs Defunkt/Jquery-Pjax

Hello.
Can you please provide a breakdown of Intercooler vs Github/Defunk Pjax.
It seems like both follow the same concept, but yours is easier to use.
Just curious what are the benefits of intercooler over, and weaknesses as compared.
Might be useful for those picking up intercooler on new projects.

https://github.com/defunkt/jquery-pjax

ic-poll should poll before time delay, not after

Right now if I set ic-poll to 15s on an element, and refresh the page, the element has no value until 15 seconds have passed.

It would be nice if there was a way to specify that I want the first poll to happen immediately on page load, rather than after the delay period. Maybe ic-first-poll="before|after" or similar?

ic-always-update

Hi, I love the library , here one thing that I found, I have a simple list(

  • One
etc..). I am using intercooler-js to take user input and ic-post which works no problem, but
on get I am returning new complete list again , what I assume that new list would "swap" the old one but instead it's "append" new list to old one . I try to use ic-always-update="true" but same thing happens.

Allow client-side event to trigger dependency change

The dependency mechanism is quite useful. As a useful extension, could a button be given an attribute such as IC-MOCK-POST-TO=/some/url, so that it invokes the intercooler dependency graph without having to do the actual post? In this case, the button click (alone) would cause an ajax load of dependent content, without saving to setup jquery style bindings to do it yourself.

ic-put-to on form element does not work

I am try to submit a html form via ic-put-to, but the form is still submitted via POST method, here is my code:

<form class="form-inline" ic-put-to="/example" ic-target="#refresh_target">
input text etc.....
<button type="submit" class="btn btn-info">Submit</button>
</form>

Do I use it wrong?

Anyway to fetch just a page fragment?

Hey there

This thing is very cool! But im wondering if there is any way to just fetch a fragment of a given URL rather than the whole thing?

Iv tried the version currently in the pull requests but it does not work for me sadly

Thanks, Danny

Firefox error when using history

I know that it is experimental, but when using firefox and using the "X-IC-SetLocation", causes an error on line 746. It works fine in Chrome, but Firefox wants all the arguments.

Setting the line to:

window.history.replaceState(_historySupport.stateCache, "", _historySupport.stateCache['restore-from']);

seems to fix the issue.

Trigger on load event not working? (lazy loading)

Hi there!

I've really been having a lot of fun with Intercooler; however, I am having trouble replicating your lazy element loading example, as specified.

http://intercoolerjs.org/examples/lazyload.html

I've been able to generate a mock response by setting "ic-trigger-on" to various mouse events and "scrolled-into-view", but when I set it to "load" I get a 404 error.

Is this a bug? Are the docs out of date? For the record, I am using version #0.9.

Thanks.

Use HTTP HEAD to determine if polling should fetch new data or not.

A HEAD request returns the Content-Length header, which as you see here can be a good indicator to check if the content has changed:

sonar_contentlength

For larger requests, a lot of bandwidth can be spared if Intercooler does a HEAD request to check if the data has been updated, instead of doing a full GET request and then comparing the data.

allow calling IC.processNodes()

I've added this to the returned object by intercooler.js:

processNodes: function(elt) {
  return processNodes(elt);
},

Reason being is, I'm using intercooler as an enhancement to pjax to load (rails) partials. At some point I might move completely to IC, since it's pretty cool, but for now this "workaround" is needed. Since I upgraded to IC 0.4.0 just now and lost my patch, I thought I'd open this feature request to have this added by default.

I'm calling it from the pjax success hook

$('#pjax-container').on 'pjax:success', ->
  Intercooler.processNodes("#pjax-container")

so that intercooler attribs are parsed correctly. I think it'd be useful to expose this by default, since I can't be the only one that wants to parse arbitary html nodes for IC stuff and insert it into the DOM.

refreshing another element which shouldn't during an is-post-to

I have a button with a ic-post-to="/machine1/manage" which will post at the right place but simultaneously, another ajax is being fired to: "machine1/" for a menu item.

This function is returning "true" for the element which contains the "machine1/" url and then the call is being made by refreshDependencies:

  function isDependent(src, dest) {
    return (src && dest) && (dest.indexOf(src) == 0 || src.indexOf(dest) == 0);
  }

How to avoid this? Is this function correctly implemented?

localStorage overflow

When using the history feature with big responds and multiple page queries I get a localStorage overflow. The history function is stop working than until I execute localStorage.clear();
It would be good if Intercooler removes old history states if the localStorage is close to overload.

Add X-IC-Prepend and X-IC-Append HTTP response headers.

I was thinking it could be cool to be able to for example post a new comment somewhere, and then you get back the HTML for how that single comment row would look, and you could append or prepend that to a list.

I am sure there are other use-cases.

use with polymer

I was wondering if intercooler can be used in a polymer project.

Add X-IC-SetPollDelay or similar

At times, it might make sense for the server to set the polling rate. This would make it possible for the server to scale down the number of polling requests it has to handle as load increases, and vice versa.

Propose that you include a header like X-IC-SetPollDelay. If the server sets this header to a value (say "30s"), Intercooler would adjust the polling rate for that partial to match.

Add ic-poll-limit or similar, exponential backoff

It would be great if there was a declarative way to specify maximum number of allowable polling events. This would make it easy to head off polling events from people who leave browsers open and walk away for days at a time, for instance.

Something like this:

<div ic-poll="5s" ic-poll-limit="200"></div>

I am aware that the server can cancel polling by sending an X-IC-CancelPolling header, but if (say) the server is throwing 500 Server Errors or 404 Not Founds that won't work. Having clients continue to hammer your server when it's down is Not Nice ;)

In fact, it would be good to see exponential backoff in the case of server errors. First HTTP 500, poll time doubled, another 500, next poll time doubled again, and after a certain number of 500s polling would be disabled. Maybe a smaller multiple.

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.