ducksboard / gridster.js

gridster.js is a jQuery plugin that makes building intuitive draggable layouts from elements spanning multiple columns
http://gridster.net/
MIT License
6.03k stars 1.2k forks source link

AJAX serialize example #317

Closed andrewhavens closed 10 years ago

andrewhavens commented 10 years ago

I've got Gridster up and running. Now I'm ready to start integrating the "save" functionality. However, I can't seem to find any examples or documentation for how to do this. There is the serialize() method which returns an array of objects:

[{"col":1,"row":1,"size_x":2,"size_y":2},{"col":3,"row":1,"size_x":1,"size_y":2}]

I can make an AJAX request to save this data, however, it is not clear how to identify each object. I tried adding a data attribute to each <li> but it did not appear in the array of objects. Can I trust the order of the array is the same as the order the <li>s were inserted? Or is there a better way to keep track?

Can you please provide an example of how this can be achieved? Also, an example on the documentation site would be useful to other people too. But I would be happy to submit a PR once I have a better understanding of how it's intended to work.

hrosenbauer commented 10 years ago

You can add more attributes by adding the serialize_params function (see http://gridster.net/#serialize_params_opt). It is called with a reference to the widget HTMLElement where you could read the id and returns a user defined object (e.g. the default return value but enriched with the ids)

andrewhavens commented 10 years ago

Thanks! It was a little confusing, but I figured it out. Here's an example to help anyone who finds this via Google.

I set a data-id attribute on the grid item, then I pull that value from the element when serialize_params gets called:

var gridster = $("#grid ul").gridster({
  widget_margins: [10, 10],
  widget_base_dimensions: [200, 200],
  serialize_params: function($w, wgd){
    { id: $w.data('id'), col: wgd.col, row: wgd.row }
  }
}).data('gridster');

$('#save-grid').click(function(e){
  e.preventDefault();
  $.ajax({
    type: 'PUT',
    url: '/grid-items',
    data: { grid_items: gridster.serialize() },
    success: function(){
      alert('Save was successful!');
    }
  });
});