GithubHelp home page GithubHelp logo

eldarion / eldarion-ajax Goto Github PK

View Code? Open in Web Editor NEW
758.0 88.0 155.0 211 KB

a library for adding declarative ajax functionality to your website

License: BSD 3-Clause "New" or "Revised" License

JavaScript 97.07% HTML 2.93%

eldarion-ajax's Introduction

eldarion-ajax

This is a plugin that Eldarion uses for all of its AJAX work.

CircleCI codecov

No more writing the same 20 line $.ajax blocks of Javascript over and over again for each snippet of AJAX that you want to support. Easily extend support on the server side code for this by adding a top-level attribute to the JSON you are already returning called "html" that is the rendered content. Unlike a backbone.js approach to building a web app, eldarion-ajax leverages server side template rendering engines to render and return HTML fragments.

This project used to be called bootstrap-ajax but the connection with Twitter Bootstrap was tenuous at best so we thought it best to rename to eldarion-ajax.

Blog Posts

Other Mentions

Demo

There is a demo project at https://github.com/eldarion/eldarion-ajax-demo/.

Installation

Download and Include

jQuery is required for this library so make sure it is included somewhere on the page prior to the inclusion of eldarion-ajax.min.js.

Copy js/eldarion-ajax.min.js to where you keep your web sites static media and the include them in your HTML:

<script src="/js/eldarion-ajax.min.js"></script>

CDN Include

<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/eldarion-ajax.min.js"></script>

CommonJS

You can also just include it in your own bundle.

npm install eldarion-ajax --save
require('eldarion-ajax');  // do this in your main bundle file and you'll be all set

Actions

There are three supported actions:

  1. a.click
  2. form.submit
  3. a.cancel

a.click

Binding to the a tag's click event where the tag has the class ajax:

<a href="/tasks/12342/done/" class="btn btn-primary ajax">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

In addition to the href attribute, you can add data-method="post" to change the default action from an HTTP GET to an HTTP POST.

form.submit

Convert any form to an AJAX form submission quite easily by adding ajax to the form's class attribute:

<form class="form ajax" action="/tasks/create/" method="post">...</form>

When submitting this form the data in the form is serialized and sent to the server at the url defined in action using the method that was declared in the form tag.

a.cancel

Any a tag that has a data-cancel-closest attribute defined will trigger the "cancel" event handler. This simply removes from the DOM any elements found using the selector defined in the data-cancel-closest attribute:

<a href="#" data-cancel-closest=".edit-form" class="btn btn-secondary">
    Cancel
</a>

Events

These custom events allow you to customize eldarion-ajax behavior.

  1. eldarion-ajax:begin
  2. eldarion-ajax:success
  3. eldarion-ajax:error
  4. eldarion-ajax:complete
  5. eldarion-ajax:modify-data

All events are triggered on the element that is declared to be ajax. For example on an anchor:

<a href="/tasks/2323/delete/" class="ajax" data-method="post">

the trigger would be fired on the <a> element. This event, of course, bubbles up, but allows you to easily listen only for events on particular tags.

Every event also sends as its first parameter, the element itself, in case you were listening at a higher level in the chain, you still would have easy access to the relevant node.

eldarion-ajax:begin

This is the first event that fires and does so before any ajax activity starts. This allows you to setup a spinner, disable form buttons, etc. before the requests starts.

A single argument is sent with this event and is the jQuery object for the node:

$(document).on(`eldarion-ajax:begin`, function(evt, $el) {
    $el.html(`Processing...`);
});

eldarion-ajax:success

This event is triggered if the request succeeds. Four arguments are passed with this event: the jQuery object; the data returned from the server; a string describing the status; and the jqXHR object:

    $(document).on('eldarion-ajax:success', '[data-prepend-inner]', function(evt, $el, data, textStatus, jqXHR) {
        var $node = $($el.data('prepend-inner'));
        $node.data(data.html + $node.html());
    });

eldarion-ajax:error

This event is triggered if the request fails. Four arguments are also passed with this event: the jQuery object, the jqXHR object; a string describing the type of error that occurred; and an optional exception object. Possible values for the third argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, the fourth argument receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

eldarion-ajax:complete

This event is triggered when the request finishes (after the above success and error events are completed). This is triggered from the document rather than the element in context as the handlers processing success messages could replace the DOM element and therefore would prevent the event from reaching your listener. The element is always passed as the first argument with this event (even if it no longer exists in the DOM). In response to a successful request, the arguments passed with this event are the same as those of the success event: the element, data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of the error event: the element, the jqXHR object, textStatus, and errorThrown.

eldarion-ajax:modify-data

This is triggered with jQuery's triggerHandler so it functions more like a callback. If you listen for it, you have to listen on the same element that you have wired up to send AJAX data on as the event doesn't bubble up. Also, it will send the original data that it serialized as a parameter and if you want to change the data at all, you must return new data from the function handling the event. Otherwise, the original data will be used.

Responses

There are three data attributes looked for in the response JSON.

  1. location - URL used for immediate redirection
  2. html - content used when processing html Directives
  3. fragments - additional content for the DOM

data.location

If location is found in the response JSON payload, it is expected to be a URL and the browser is immediately redirected to that location. No additional HTML processing is performed.

data.html

The data.html response element is typically used for insertion or replacement of existing DOM element content. Exactly how data.html is used depends on one or more processing directives.

Processing directives are defined by attributes added to the event-handling class="ajax" element. They are linked to handlers as described in Handlers: A Batteries-Included Framework.

Each processing directive is assigned a CSS selector. Since a CSS selector can be written to address multiple different blocks on the page at the same time, large segments of the DOM can be modified with each directive.

All processing directives are executed for each event and any number of directives may be combined.

Processing Directives

data-append

Append response JSON data.html to the element(s) found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-append=".done-list">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-clear

Clear the .html attribute of each DOM element found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-clear=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-clear-closest

Invoke data-clear functionality using jQuery's closest method to interpret the selector.

data-prepend

Prepend response JSON data.html to the element(s) found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-prepend=".done-list">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-refresh

Define which elements get refreshed. Matching elements are refreshed with the contents of the url defined in their data-refresh-url attribute.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...</div>

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-refresh=".done-score">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

In this example, .done-score will fetch (GET) JSON from the url defined by data-refresh-url, then replace itself with the contents of response JSON data.html.

data-refresh-closest

Invoke data-refresh functionality using jQuery's closest method to interpret the selector.

data-remove

Remove DOM elements found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-remove=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-remove-closest

Invoke data-remove functionality using jQuery's closest method to interpret the selector.

data-replace

Replace the element(s) found in the specified CSS selector with response JSON data.html.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-replace=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-replace-closest

Invoke data-replace functionality using jQuery's closest method to interpret the selector.

data-replace-closest-inner

Invoke data-replace-inner functionality using jQuery's closest method to interpret the selector.

data-replace-inner

Similar to data-replace functionality, but replaces the element(s) .html attribute.

A Complex data.html Processing Directive Example

This example shows combined use of data-append, data-refresh, and data-remove attributes as data.html processing directives.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...</div>

<div class="done-list">...</div>

<div class="results"></div>

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-append=".done-list"
                                                          data-refresh=".done-score"
                                                          data-remove=".results">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

It is rare to use many processing directives combined like this. Usually just one or two suffice.

data.fragments

Response JSON data.fragments should contain a list of key/value pairs where keys are the selectors to content that will be replaced, and values are the server-side rendered HTML content replacing elements that match the selection.

data.append-fragments

Similar to data.fragments. Each fragment value is appended to the element(s) found in the key CSS selector.

data.inner-fragments

Similar to data.fragments. Each fragment value replaces the .html attribute for the element(s) found in the key CSS selector.

data.prepend-fragments

Similar to data.fragments. Each fragment value is prepended to the element(s) found in the key CSS selector

Response Data Pro Tip

Both data.html and data.fragments are processed in a single response. This gives you the ability to replace a submitted form with data.html content while also updating multiple fragments of content on the page.

Action Attributes

The following attributes are used by eldarion-ajax when processing supported Actions.

data-cancel-closest

Used on an <a> anchor tag, triggers the cancel event handler, which removes from the DOM any elements found in the specified CSS selector.

<a href="#" data-cancel-closest=".edit-form" class="btn btn-secondary ajax">
    Cancel
</a>

data-method

Defines the request method, i.e. "POST". If this attribute is not provided, the request method defaults to "GET".

<a href="/tasks/2323/delete/" class="ajax" data-method="post">

data-refresh-url

Specify a URL which will return HTML content for the element.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...</div>

Handlers: A Batteries-Included Framework

The eldarion-ajax events allow you to code handlers which customize actions for server responses. Many handlers are included (see Processing Directives), but here is a quick primer for writing your own.

$(function ($) {
    CustomHandlers = {};

    CustomHandlers.prototype.replaceFadeIn = function (e, $el, data) {
        $($el.data('replace-fade-in')).replaceWith(data.html).hide().fadeIn();
    };

    $(function() {
        $(document).on('eldarion-ajax:success', '[data-replace-fade-in]', CustomHandlers.prototype.replaceFadeIn);
    });
}(window.jQuery));

This gives you a lot of flexibility. For example, if you don't like how the batteries included approach treats server response data, you can drop inclusion of eldarion-ajax-handlers.js and write your own handlers.

Commercial Support

This project, and others like it, have been built in support of many of Eldarion's own sites, and sites of our clients. We would love to help you on your next project so get in touch by dropping us a note at [email protected].

eldarion-ajax's People

Contributors

bwarren2 avatar callumacrae avatar davelowe avatar dirish avatar grahamu avatar josemalonsom avatar jtauber avatar kennethlove avatar msurguy avatar paltman avatar shabda 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

eldarion-ajax's Issues

Option NOT to clear form fields after submitting

I think that clearing all form fields after submitting isn't the right decision. It should be optional. If we want to add many new items to the database autoclearing works perfect. But if we want to change info in users profile, for example, the fields shouldn't clear. Moreover, if we have any errors on the server side (wrong captcha-code, validation problrms, etc.) we want just to receive the error message without clearing the form.

Do not clear form automatically

There is no good way to know what fields should be cleared and shouldn't be cleared as this is a site level decision. Now that there are events that the site dev can hook, I think it's best done there.

Create a pluggable system

I'd like to figure out a clean way to break out the parts of processData.

The method continues to grow and I don't think it's sustainable/maintainable. I'd like to see something developed that allows "plugins" to be written to extend what processData can do. Ideally, this would mean that each of the parts of the current processData are extracted out to their own modules/plugins and included in this repo and a compiled version of bootstrap-ajax includes all of the plugins but users are also free to include only the ones they want or write their own extensions/plugins to customize certain aspects of the behavior and/or add entirely new processing methods.

I have some ideas for how I would do this but welcome input from more advanced javascript developers.

Problem with refresh

Hi,

I have a problem using "refresh" and "replace".
This is the code:

If I use data-refresh as in this previous code, the "data-left" div, is not changing.
If I use "replace", the "data-left" div disappear.

Could you help? Are there any errors in my code?

Refresh a data-refresh-url item

Hello,

I'd like to know how could I refresh the following div by clicking on a button or anchor.
I tried the following code:

< div id="my-div" data-refresh-url="info">

< a data-refresh="#my-div" > Refresh! < /a>

Is it possible to request an item refresh without sending a Get request to the page?

Thanks in advance!

Compatibility with jquery_ujs in Rails?

Hi,
I'm trying to use your js, which I find awesome, in a Rails app. Get requests are ok but I'm stucked into post/put requests.
The problem is that for each post/put there are two requests that are routed to the backend, the first one is successfully completed, the second one fails:

Started POST "/todos/undone/6" for 127.0.0.1 at 2013-07-13 09:23:57 +0200
Processing by TodosController#mark_undone as JSON
  [...]
  Rendered todos/_todo.html.erb (2.5ms)
Completed 200 OK in 52ms (Views: 0.8ms | ActiveRecord: 23.8ms)


Started POST "/todos/undone/6" for 127.0.0.1 at 2013-07-13 09:23:57 +0200
Processing by TodosController#mark_undone as HTML
  [...]
  Rendered todos/_todo.html.erb (1.9ms)
Completed 406 Not Acceptable in 15ms (ActiveRecord: 3.0ms)

At the first attempt everything is accomplished, giving back a json with the html content that the frontend is waiting for. The second one fails because the HTML response is not rendered by the backend (which is correct, since I've to send back a json to the eldarion-ajax success).

I do not know if this is happing due a conflict between jquery_ujs, which include all the functionalities of rails.js for the standard rails ajax requests, with eldarion-ajax.

Someone has an idea regarding that?
Thanks!

Notice: if I disable jquery_ujs the backend response is the following:

WARNING: Can't verify CSRF token authenticity
  [...]
Completed 401 Unauthorized in 10ms

Issue posting form with AJAX

Hello,

I am using the Jasny File Upload widget for Twitter Boostrap to give easy file controls on a form.

I previously had version 0.6.0 of this ajax plugin and everything was working ok in that my form would post the data in AJAX and non-AJAX modes.

I am using bower to maintain my plugins and updated AJAX to the latest version. I then updated the links in my HTML to point to the new 'eldarion' files. However now when I post my form, using AJAX, with the image the file details are not sent and my PHP array is empty. (If I do the same without the AJAX class set on the form all is OK).

I have not updated the version of Jasny File Upload. I think there must be a clash with JavaScript or CSS but I cannot find out where.

I realise that this is not the easiest one to fix as it is working with another plugin. However it did work and now after the update it does not.

Any help is gratefully appreciated. Please let me know if any more information is needed.

Thanks very much, Russell

Replace html only

It would be useful to be able to replace eveything within a container, leaving the container intact.
ie. data-replace-html

can not support IE?

set response content type to text/html or text/json, one output download file,the other one just view.
anyone can help you? but,chrome,firefox work well!
IE open http://uk013.o1.gondor.io/ also download file !
thx

callback event

Is it possible to add a custom callback after the data comes back? Something like data-callback and have that function executed so you can do other processing (form validation messages, custom animations, call other events).

Add first class support for bootstrap modals

There was a partial attempt at this in #13 which I closed after suggesting a work around, but it would be nice to have the modals driven via declarative markup.

Use Cases

  1. Display a modal that is a server rendered content fragment that an a.ajax click fetches
  2. Close the modal on posting of a form rendered in the modal
  3. Display secondary content in the modal after posting a form that was rendered initially in the modal.

Cases 1 and 2 are fairly easy to solve (at least I am pretty sure), the case in number 3 is a bit tricky as we want to avoid the modal closing and reopening and want the modal to just replace the insides instead of flashing about on the screen. One approach would be to have secondary fragments that were just replaced and not the entire div.modal but that could get out of hand in managing a ton of different templates.

Open to ideas/suggestions on this.

Currently, I think the best work around there is for this is to load the modal fragment as hidden and have the following script fragment to remove excess backgrounds and show the modal (this seems to work for me for most cases but would like to alleviate the need of evening having to do this):

<script>
    $(".modal-backdrop").remove();
    $("#my-modal").modal("show");
</script>

where #my-modal is referencing the id you place your modal div to make it unique.

Add "start" event

I'd like be able to display my own custom spinner (which backdrops the whole page and places a spinning bar on top). I was thinking the easiest way to deal with this would be to hook into the success and error events however I would need a start event too.

Would it be possible to add an event like:

$this.trigger('bootstrap-ajax:start');

somewhere near where spin() is called?

Noob question (forms)

Hi,

i am trying to extend your demo with another field in the form but unfortunately I am not getting anything to Django:

    <form class="form-inline ajax" method="post" action="{% url task_add %}" data-append="#tasks">
        {% csrf_token %}
        <div class="input-append">
            <input type="text" class="span4" name="label" placeholder="Enter a stream name...">
        </div>

        <div class="input-append">
            <input type="text" class="span4" name="phonenumber" placeholder="Enter a phonenumber...">
        </div>
    </form>

Added the phonenumber field:

views.py:

    @require_POST
    def add(request):
        session = Session.objects.get(session_key=request.session.session_key)
        if Task.objects.filter(label__exact=request.POST.get("label")).exists():
          data = _task_data(request,Task.objects.get(label__exact=request.POST.get("label")),True)
          return HttpResponse(json.dumps(data), mimetype="application/json")
        task = Task.objects.create(
            session=session,
            label=request.POST.get("label"),
            phonenumber=request.POST.get("phonenumber")
        )
        data = _task_data(request, task)
        return HttpResponse(json.dumps(data), mimetype="application/json")

models.py:

    class Task(models.Model):
        session = models.ForeignKey(Session)
        label = models.CharField(max_length=100)
        done = models.BooleanField(default=False)
        phonenumber = models.CharField(max_length=10)

I am sorry but I am really new to django / ajax.

File handling?

Can eldarion-ajax handle file uploads?

In my testing, value of input field is sent via post, but the FILES is empty. So investigation whether this is even supported comes in mind!

Thanks!

Add current element shortcut

As I know, data-* attributes use css selector to locate the target to operate on.

But I can not locate the current element unless I define an id for it, which is not convenient.

So a shortcut, such as '.', for the current element can be very helpful.

a.click() throws exception

Sometimes while @ a.click() jquery throws an exception at line :8416

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

console shows :

s.hasContent as 'true'.
s.data as NULL.

I'am a newbie in javascript. Hope this info helps.

Triggering of success and error events

This is a suggestion/enhancement that didn't warrant a fork and merge and doesn't fix a bug or error. At the end of the processData and processError functions, you trigger events that can be used to notify the application when data is processed or and error occurs. My suggestion is to modify the code to trigger the event on the element itself instead of document. The code currently looks like this:

$(document).trigger('bootstrap-ajax:success', [data, $el]);

I would recommend that it look like this:

$($el).trigger('bootstrap-ajax:success', [data]);

That way when I bind to it I can get events on my specific form or anchor that's posting back like this:

$("#myform").on("bootstrap-ajax:success", function(e, data) {
   ....
});

The current approach is functional, but I believe that the approach I am presenting is more in the spirit of jQuery and bootstrap.

Thank you for your consideration.

data-append

This is the only thing I can't seem to get to work. I have added the ajax class to my form and it gets submitted there but I can not retrieve the data from the page that it is getting submitted to. It will not display where I want it to. How do I do this? I have been altering my code for about a day now and can't figure it out. Any and all help would be great.
All I want is the data to show up that is getting posted.

Thanks

data-replace-closest (improvement to naming)

This is more a suggestion than an issue report.
I'm usually the programmer who delves into fixing the messy bugs in legacy code. As such I've read a lot of code. Imagine if instead of

<class="form ajax"  data-replace="#message-form"...>

It read:

<class="form ajax" data-ajax-replace="#message-form"...>

Then even to someone not familiar with eldarion-ajax, it would be pretty clear the class and the replacement are connected.

Ability to change ajax url in begin event (question)

Not sure it is even possible (doesn't seem to be). Only trying because docs do say that Begin is fired "before" the event occurs, but given how asynchronous it all is, I imagine the event is fired and then continues on down the chain.

Looking to append query parameters to the URL when link is clicked / just before event is fired.

Have a couple other options, but this was the cleanest (if it worked).

Changing the $el.attr("href") is too late (and updates it for all future link clicks. Don't have any access to the event parameters themselves that I can discern.

Spinner does not stop / hide

I love the project but for some reason, a spinner activated via setting the data-spinner attribute, never stops.

A look into the code indicated, that actually stop_spin() is never called anywhere.

Is there a plan to fix this?

execute bootstrap-ajax form by javascript

Hi, I am using bootstrap-ajax and everything works fine, except that now am trying to execute some forms using javascript:

    <script type='text/javascript'>
        function chamaForm(myForm, myString)
        {
            //document.write(myForm)

            //Cria o <input type = hidden name='myString' value=myString>;
            var i = document.createElement('input'); 
            i.setAttribute('type','hidden');
            i.setAttribute('name','filtraCloud');
            i.setAttribute('value', myString);
            myForm.appendChild(i);

            myForm.submit();    
        }
    </script>

This way, form´s request is not a XHR, but a standard HTTP Request and I don´t know why.
Can you help me? I have already moved my javascript before and after bootstrap-ajax loading, whith no success.

I am not sure if this is the rigth place to post this question, so I am sorry if it is not.

Could use a more specific 'Accepts' HTTP header

Currently, the requests generated use */* as the Accept header. Some APIs will return HTML, or some other default, in that case.

My limited tests show that we can be more specific by adding a dataType argument to the .ajax() call:

$.ajax({
  url: url,
  type: method,
  dataType: 'json', // new argument
  statusCode: {
    200: function(data) {
      processData(data, $this)
    },
    500: function() {
      processError($this)
    }
  }
})

This will create requests with the following Accept header (tested in Chrome dev tools):

application/json, text/javascript, */*; q=0.01

Haven't tested all the user cases, but it doesn't seem to break anything.

There may be additional benefit in using jQuery.getJSON() instead of jQuery.ajax().

Handlers do not work if html is empty string

To replicate:

return this (after) jsoning

`data = {"html": ""} from a view.

Html is:

<a href="/foo/" class="ajax" data-replace="#some-id">

The object doesn't get replaced.

Easy to work around by adding a space in returned html, but hard to debug if you hit this issue.

`data = {"html": ""}

Post Anchor Attributes

Greetings,
I'd like to know how could I send an anchor attribute to a PHP file with a Post method:

a href="favourites" class="btn btn-primary ajax votebtn" data-method="post" data-refresh=".votecount" data-replace=".votebtn" data-user="3987"

In this example, I'd like an user to Vote some content of my website, however I'd need to send the data-user attribute to my PHP controller in order to perform the vote.

Thanks you in advance!

data-timeout doesn't work in a html fragment

because the handlers are attached with:

$('[data-timeout]').each(Ajax.prototype.timeout);
$('[data-interval]').each(Ajax.prototype.interval);

if some html fragments come back with data-timeouts in them they won't have the handler attached.

The library should reattach to fragments.

Support multiple refresh elements

Enable multiple elements to refresh by using data-refresh=".ele1, ele2"
Something like:

if (refresh_selector) {
        refresh_selector = refresh_selector.split(',');
        $.each($(refresh_selector), function(index, value) {
          $.getJSON($(value).data('refresh-url'), function(data) {
            $(value).replaceWith(data.html)
          })
        })
      }

[Proposal] Pass all data vars via AJAX calls

Instead of having to explicitly create a data-data="var1:1,var2:#var2" attribute, wouldn't it be better to loop through all data variables and pass them into the ajax calls.

For example on the current version:

<a href="#" class="btn btn-default ajax" data-method="post" data-replace-inner="#grid" data-page="1" data-data="action:page,page:1,grid_state:#grid_state"><i class="icon-chevron-left"></i></a>

Could be changed to:

<a href="#" class="btn btn-default ajax" data-method="post" data-replace-inner="#grid" data-page="1" data-action="page" data-gridstate="#grid_state"><i class="icon-chevron-left"></i></a>

I know it doesn't look like much but the benefits are great. For example in the first one I have to declare data-page="1" in addition to adding it to the data-data="" because I use some javascript to manipulate the page using the data-page attribute. However I also need to pass it to the ajax request to use it server side. Another benefit is that we gain access to all the existing functionality such as knowing the method (get or post) to check for variables, what partials we are replacing, etc.

It could be made backwards compat by checking for data-data and using that else passing all data attributes.

add event(s) for refreshing/replacing elements

There is a issue when refreshing or replacing element blocks that have had js events wired up to them. If they are just simple direct event handlers like say a click event, then once can just use live or the latest equivalent, however, in cases of using something like bootstrap-tooltip or any other plugin that itself does things including wiring up it's own event handlers internally, you have to currently resort to adding something like this within the fragment being reloaded:

{% if request.is_ajax %}
<script>
    $(selector).plugin_name();
</script>
{% endif %}

For bootstrap's tooltip, you actually have to remove previous tooltips as well.

I think the proper way to go is to eliminate the need for this request.is_ajax by adding events to bootstrap-ajax so that you can hookup a live("ajax-refreshed", function(){}) or the like so that you can put all your hookup logic in one place and not litter it about in your fragments.

Add ability to replace contents of a container

There have been a number of people (#12, #11, and perhaps others) who have suggested this and/or provided their own solutions.

I really want to limit how much is added to this library so as to keep it lean and avoid that bloat that happens to these types of libraries over time with all the tack-ons. However, this is a common enough one that my plan is to add the following additional attributes:

data-replace-inner
data-replace-closest-inner

These will use html() instead of replaceWith()

add a data-clear attribute

Doesn't have to be called data-clear (could be data-remove) but it would be handy to be able to specify not only selectors that are to be refreshed but ones that are just to be removed.

I guess you could have two: data-clear (or data-empty) and data-remove which differ in that the latter removes the selected element(s) whereas the former just clears their content to be empty.

Example / Demo

Cool proj!

A demo / example page would be super handy!

Success events not triggered when element is replaced

The bootstrap-ajax:success event is not triggered when data-replace or fragments replaces $el.

e.g.

// this listener is never called
$('body').on('bootstrap-ajax:success', function() {
   console.log('bootstrap-ajax:success triggered');
});
<div id="my_div">
    <a href="/some/ajax/handler" class="ajax" data-replace="#my_div">Hit me</a>
</div>

I noticed issue 24 (Triggering of success and error events) #24 changed the behaviour to trigger on the element itself.

I'm not sure what the solution is here. Perhaps to trigger on the document if the element has been removed from the DOM?

Add auto-refresh support

In many websites there are always some html blocks that load in ajax way to increase site load speed.

And some html blocks need refreshing periodically.

So auto-refresh support may help a lot.

Raise some custom events

Hi just wondering if you'd be keen to add a custom event that fires at the end of the processData method.

Something like this

$(document).trigger('Ajax:success', [ data, $this ]);

That way I could listen for that event and do any minor things not covered by the library? Basically I want to be able to initialise a jQuery plugin on the newly append elements that have come back from the server. I could use jQuery livequery but everyone frowns on that :)

This is the listener:

    lazyloadimages();

    $(document).bind('Ajax:success', function(evt, data, $el) {
        if ($el.attr('data-replace-closest') == '.load-button') {
            lazyloadimages();
        }
    });

    function lazyloadimages() {
        $("img.lazy").lazyload({ effect : "fadeIn", event : 'scrollstop' });
    }

I was also playing around with the idea of the server being able to send back multiple fragments, each fragment consisting of a command, html and a selector. Would add some pretty cool scenarios for example not having to use refresh:

In C# on the server it would look something like this:

            /* JUST thinking out loud here
            // append
            // replace
            // remove (just send the selector)
            // refresh (send a url for the ui to requery)
            // we could return fragments like this:

            return Json(new 
            {
                fragments = new [] {
                    new {
                        command = "append",
                        selector = ".result-list",
                        html = "<p>Take out the trash</p>"
                    },
                    new {
                        command = "replace",
                        selector = ".task-counter",
                        html = "<span class='count'>5</span>"
                    }
                }
            });
            */

To slow

i don't know exactly why, but if i load the page and click an ajax link directly after loading, i get this in my data-replace-inner element: {"html":"\nblaescapedhtmlbla"}
it seems the loading of eldarion-ajax.js file takes to long, so i placed the script tag with the eldarion-ajax.js file in the head and the bootstrap.min.js on the end of the body tag. Now it works a little bit better but not perfect :(
I hope somone can help me

Properly document the library

There have been a lot of features added since the initial pass at documenting this library. Bring things up to date.

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.