I have an unordered list (generated by jinja2 under Flask) which the user can re-order interactively, using mouse or keyboard. Each list item has a data-dbid attribute (the database key) and a data-seq attribute (defining the place of the item in the list).
The data-seq attribute is initially set by jinja2 and then updated by the jquery code that enables the re-ordering to reflect any user changes to the sequence.
Once the user has finished re-ordering the list I want to do a simple post of json to the server of data-dbid and data-seq key/value pairs so the sequence changes can be persisted to the db.
For a 3-row list the resultant json should therefore look something like:
[
{ "dbid": 123, "seq": "1" },
{ "dbid": 456, "seq": "2" },
{ "dbid": 789, "seq": "3" }
]
I am struggling to create the json, without iterating the list and building it.
I was expecting to be able to use JSON.stringify, with the class of the list items as the selector and specifying the keys of the required attributes, but this doesn't work (I get an empty string).
HTML/Jinja2 code snippet:
<ul class="ais-table" id="ais-types">
{% for ListType in ListTypes %}
{% set itemId = (loop.index|string) %}
{% set itemDbId = (ListType.id|string) %}
{% set itemSeq = (ListType.sequence|string) %}
<li class="ais-row" id="{{itemId}}" data-dbid="{{itemDbId}}" data-seq="{{itemSeq}}">
<div class="ais-row-name">
{{ ListType.name }}
</div>
</li>
{% endfor %}
</ul>
The JQuery code:
$(document).ready(function(){
$('#btnSave').bind('click', function() {
var listData = $(".ais-row");
var jsonData = JSON.stringify(listData, ["dbid", "seq"]);
alert(jsonData); // Test purposes only
// AJAX code here
});
});
If I use the JSON.stringify code above then the result is an empty string. I'm not sure whether, for data-* attributes, I should be specifying "dbid", "data-dbid" or even "dataDbid" in the replacer array, but I've tried all 3 and none work.
If I take out the replacer array:
var jsonData = JSON.stringify(listData);
... then I get all the attributes, including "dbid" and "seq" (which proves they are at least being being found). I've also tried writing a replacer function but that also did not work (key value doesn't seem to be passed and I end up with all attributes in the json):
let replacer = function (key, value) {
alert(key); // Displays "undefined"
if((key == "dbid") | (key == "seq")) {
return value;
} else {
return undefined;
}
}