Using serializeArray for objects without form?

I am trying to publish some data created from some non-format elements, but I cannot hack it.

How to create an array in the same format as serializeArray() with form fields?

I tried several variations of this, but only picks up the latest .active tag.

 $('li.tag.active').each(function() { values = {}; values['tagID'] = $(this).attr('id'); }); $.post("/scripts/php/process.php",{ 'data': data, funcName : 'tagResults' },function(results){ $("#results").html(results); }) 
+4
source share
4 answers

ok - found this at the end, which works exactly as if it were input fields with serializeArray () ...

 function getTags(){ var data = new Array(); $('li.tag.active').each(function() { data.push({ 'name':$(this).attr("name"), 'value':$(this).attr("id")}); }); $.post("/scripts/php/process.php",{ 'data': data, funcName : 'tagResults' }) } 
+5
source

Adding this function to your JS code allows you to serialize any object with the attributes "name" and "value". I usually use it to serialize forms. I know that you said that these controls are formless, but I would suggest that this can be used to serialize any object with the name / value attribute. It also looks simple enough to change it to look for other attributes of an object, such as an ID. It's hard to say exactly what you are doing there, because you are not showing the definition of "data" or the use of "values"

  $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; 

Then just add it to url string

 var dataToPassToAjax = 'allData=' + myObject.serializeObject(); 

If you pass only one value, you do not need to serialize.

 $.post("/scripts/php/process.php",{ 'data': 'data=' + $('li.tag.active').id, funcName : 'tagResults' }). 

then in process.php just get the value $ _ REQUEST ['data'] , and it will have your identifier

+2
source

The best answer I've seen from Ob. and Guntram: jQuery serialize / serializeArray from an element that is not a form

$('div :input').serializeArray()

In addition to the inputs, it selects select and textarea. Sweet.

+1
source

Using this function, you can make any set of elements serializable:

 function makeSerializable(elem) { return $(elem).prop('elements', $('*', elem).andSelf().get()); } 

Then you can use it as follows:

 var arr = makeSerializable('li.tag.active').serializeArray(); 

or

 var $elem = $('li.tag.active'); var data = makeSerializable($elem).serialize(); 
0
source

All Articles