How to Add to a Serialized Array

Can I add data to an already serialized array?

.serialize returns a string, so you can always modify the string, but I would not recommend this, string manipulation can get messy.

Instead, use .serializeArray [docs] to create an array representation of the data and then add the data to it. Each element of the array is an object with a name and value property:

var vals = $("#post").find('input,select').serializeArray();
vals.push({name: 'nameOfTextarea', value: CKEDITOR.instances.ta1.getData()});

All jQuery Ajax methods will understand this structure and serialize the data properly. In case you want to create a serialized string (just like .serialize), you can pass the array to $.param [docs]:

var query_string = $.param(vals);

PHP how can i append data into a serialized array

Yes.

function addItem($serializedArray, $item)
{
$a = unserialize($serializedArray);
$a[] = $item;
return serialize($a);
}

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

append data in serialized array with php

First of all, you do not escape data passed to your script. You have to do it with:

$x[0] = mysql_real_escape_string( $_GET['fname'] );

Also you do not need to set index, so:

$x[] = mysql_real_escape_string( $_GET['fname'] );

It will append data to the end of array.

If you want to add new data to the existing serialized array, you need to unserialize it, add data and serialize again:

$x   = unserialize($x);
$x[] = 'something else';
$x = serialize($x);

How to add to a serialized array

You can pass a class to serialize:

class User < ActiveRecord::Base
serialize :recent_messages, Array
end

The above ensures that recent_messages is an Array:

User.new
#=> #<User id: nil, recent_messages: [], created_at: nil, updated_at: nil>

Note that you might have to convert existing fields if the types don't match.

How do I use a form to fill a serialized array in a Rails 4 model?

I got it to work. I'm still a little hazy on how I did this, but here are the pieces I used in Rails 4.2:

First, I created a new text column called :other_photos and migrated it. Next:

In the model:

serialize :other_photos, Array

In the controller:

Set permissions:

params.require(:record).permit(:name, :caption, {:other_photos =>[] })

def create
@record = Record.new(record_params)
@record.other_photos = params[:other_photos] # this was the piece that held me back

...

end

In the view:

<%= form_for @record do |r| %>
<%= text_field_tag "other_photos[]" %>
<%= text_field_tag "other_photos[]" %>
<%= text_field_tag "other_photos[]" %> # "r.text_field" didn't work for some reason

...

<% end %>


Related Topics



Leave a reply



Submit