14

I have this piece of code in my PHP code:

while ($row = mysqli_fetch_assoc($result))
{
    extract($row);
    echo "<tr>";
    echo "<td bgcolor='#FFFFFF'><input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
    echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
    echo "</tr>";
}

In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,

var selectedbooks = $("book_form").serialize();
alert (selectedbooks); 

In the alert message box, i did not get any value (empty string).

Previously when i am using Prototype, it worked nicely.

abatishchev
  • 98,240
  • 88
  • 296
  • 433

14 Answers14

22

easy: serialize().replace(/%5B%5D/g, '[]')

Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
9

I have come up with a method that will, when the data is sent using post

on the other side lets you access your elements using $_['post']['name']

If it is an array (eg a multiple select) then on your server you can access it as an array again $_POST['myselect'][0]...

Code: Function to serialize form data for post

function serializePost(form) {
    var data = {};
    form = $(form).serializeArray();
    for (var i = form.length; i--;) {
        var name = form[i].name;
        var value = form[i].value;
        var index = name.indexOf('[]');
        if (index > -1) {
            name = name.substring(0, index);
            if (!(name in data)) {
                data[name] = [];
            }
            data[name].push(value);
        }
        else
            data[name] = value;
    }
    return data;
}
Hailwood
  • 89,623
  • 107
  • 270
  • 423
2
var arTags = new Array();

jQuery.map( $("input[name='tags[]']") , function(obj,index)
{
   arTags .push($(obj).val());
});

var obj = {'new_tags'           : $("#interest").val() ,
           'allready_tags[]'  : arTags };

var post_data = jQuery.param(obj,true);

$.ajax({
      type :  'POST',
      url  :  'some_url',
      data :  post_data,
      dataType : "html",
      success: function(htmlResponse)
      {

      }
});
1

Prototype / Scriptaculous serialize functionality for jQuery:

<script>
function toObjectMap( queryString )
{
    return '{\'' + queryString.replace(/=/g, '\':\'').replace(/&/g, '\',\'') + '\'}';
}
</script>
...
<div id="result"></div>
...
<form onSubmit="$('#result').load( ajaxURL, toObjectMap( $('#formId').serialize() ) );" ...>
...
  • it's all good but the problem is that you're passing the form elements to your function through $.serialize that will reolace the stuff we don't wanna replace anyway and even though I haven't looked at the source code I think serialize does all this anyway but it does some extra stuff we dont want it to do like replace '[' and ']' – Neo Oct 10 '10 at 00:21
1

@Tomalak You can use the square brackets characters "[" and "]" within XHTML see http://www.w3.org/TR/xhtml1/dtds.html#dtdentry_xhtml1-transitional.dtd_input

So this means that a name can contain many different characters legally within XHTML, although it doesn't make much sense to use slashes or brackets. PHP supports the use of array notation in form names, so you could be missing a trick if you don't use array notation in some instances.

1

work correctly jquery =>

var data = $('form').serialize();
            $.post(baseUrl+'/ajax.php',
                    {action:'saveData',data:data},
                    function( data ) {
                        alert(data);
                    });

php =>

parse_str($_POST['data'], $searcharray);
    echo ('<PRE>');print_r($searcharray);echo ('</PRE>');

output =>

[query] => 
[search_type] => 0
[motive_note] => 
[id_state] => 1
[sel_status] => Array
    (
        [8] => 0
        [7] => 1
    )

and You can do whatever what you want like with array data, thanks to Aridane https://stackoverflow.com/questions/1792603

Community
  • 1
  • 1
Deniska Axe
  • 154
  • 1
  • 4
1

jQuery 1.4

var myform = $("book_form").serialize();

decodeURIComponent(myform);
Philo
  • 11
  • 1
0
var data = $(form).serialize();
$.post('post.php', '&'+data);
FDisk
  • 8,493
  • 2
  • 47
  • 52
  • +1: If this is just to submit it using .post() or the like, although the documentation shows it using JSON'ified data, it will accept serialized data just as well: see http://api.jquery.com/jQuery.post/#example-3 – Mala May 19 '10 at 03:30
0

If you have to post that array only and not other input fields, this is a clean and quick solution:

var selectedbooks = $('book_form input[name^="bookArray["]').serialize();
alert (selectedbooks); 

Explaination:

The selector ^= selects all elements with a name attribute value starting with 'bookArray', the open square bracket '[' makes sure the element is the array we want to serialize and not just a variable starting with the string 'bookArray'.

Frank
  • 809
  • 1
  • 10
  • 12
0

You have to replace left square brackets and right square brackets with this:

data: $(this).serialize().replace(/%5B/g, '[').replace(/%5D/g, ']'),
bkingg
  • 15
  • 4
0

You may need to change your PHP as @Tomalak suggests, but you will also need to change your javascript. To reference a named element use the #name selector:

var selectedbooks = $('form#book_form').serialize();;
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

Thanks Tomalak.

In the PHP file, I am using the following code now:

while ($row = mysqli_fetch_assoc($result)) {
    extract($row);
    echo "<tr>";
        echo "<td bgcolor='#FFFFFF'><input id='$book_id' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
        echo "<td bgcolor='#FFFFFF'>$book_name</td>";
    echo "</tr>";
} // while

**The book_id is unique.

Using tvanfosson solution, now i am able to get array of input value

var selectedBooks = $('form#book_form').serialize(); alert (selectedBooks);

From the alert message box, I get ==> bookArray%5B%5D=T2.05&bookArray%5B%5D=T2.81

Now, when I sent the serialize input value to PHP file using JQuery

var selectedBooks   = $('form#book_form').serialize();
alert (selectedBooks);

var url = 'saveBookList.php';

// Send to server using JQuery
$.post(url, {bookArray: selectedBooks}, function(responseData) {
    $("#save-result").text(responseData);
});

Inside saveBookList.php to process the serialize form, i got this error "Invalid argument supplied for foreach()".

Inside saveBookList.php,

// If you have selected from list box.
if(isset($_POST['bookArray'])) {

    // Get array or bookID selected by user
    $selectedBookId = $_POST['bookArray'];
    echo $selectedBookId;

    foreach($selectedBookId as $selectListItem) {
        echo "You sent this -->" . $selectListItem . "\n";
    }
}

The PHP code above works fine if i am sending using Prototype.

For Prototype when i do echo $selectedBookId;

I got Array.

For JQuery, when i do echo $selectedBookId;

I got ==> bookArray%5B%5D=T4.11&bookArray%5B%5D=T4.38

My question, does jQuery support array value for post method?

Manoj Sharma
  • 1,467
  • 2
  • 13
  • 20
  • You are missing the point: You are *not* sending an array to the server. HTTP Posts do not work like this. You send a comma-separated list of values: $selectedBookId is like "1,2,3,4,5". To make an array again, use: $selectedBooks = explode("," $selectedBookId); – Tomalak Nov 20 '08 at 10:03
  • By the way: You still have "name='bookArray[]'" in your PHP, which is just *wrong* in HTML. Change it to simply "name='books'". As I said, there is no such thing as an array of form values in HTML. – Tomalak Nov 20 '08 at 10:07
  • You should really use var_dump() more often in your PHP. You would have spotted *at once* that you are not dealing with an array in the first place. – Tomalak Nov 20 '08 at 10:10
  • 1
    @Tomalak: `varname[]` is needed for PHP to handle groups of checkboxes (or any inputs for that matter) as an array server side. – nikc.org Aug 25 '09 at 14:32
0

Problem solved! Here is what i did.

Inside PHP file to create rows of dynamic checkboxes,

  while ($row = mysqli_fetch_assoc($result))
  {
   extract($row);
   echo "<tr>";
   echo "<td bgcolor='#FFFFFF'><input name='books' type='checkbox' value='$book_id' />$book_id</td>";
   echo "<td bgcolor='#FFFFFF'>$book_name</td>";
   echo "</tr>";
  } // while

I do not use JQuery $.post method anymore. I changed my code to the following

    var my_query_str = '';

$("input[@type='checkbox'][@name='books']").each(
  function()
  {
    if(this.checked)
    {
           my_query_str += "&bookArray[]=" + this.value;
    }
  });


$.ajax(
{
    type: "POST",
    url: "saveBookList.php",
    data: "dummy_data=a" + my_query_str,
    success:
        function(responseData)
        {
            $("#save-result").empty().append(responseData);
        },
    error:
        function()
        {
            $("#save-result").append("An error occured during processing");
        }
});

Now, inside saveBookList.php page, value of $_POST['bookArray'] is an Array. Yey! Yey!

I do hope and wish the $.post method of JQuery can support array data type as Prototype does. :)

  • it's not a problem with jQuery Post, it's with serialize you can do this: var my_query_str = ''; $("input[@type='checkbox'][@name='books']").each( function() { if(this.checked) { my_query_str += "&bookArray[]=" + this.value; } }); jQuery.post("saveBookList.php","dummy_data=a" + my_query_str ,function(responseData){ $("#save-result").empty().append(responseData); }, error: function() { $("#save-result").append("An error occured during processing"); } }); – Neo Oct 10 '10 at 00:25
0

it's not a problem with jQuery Post, it's with serialize you can do this:

    var my_query_str = ''; 
    $("input[@type='checkbox'][@name='books']").each( function() { 
       if(this.checked) { my_query_str += "&bookArray[]=" + this.value; } 
    }); 
   jQuery.post(
      "saveBookList.php",
      "dummy_data=a" + my_query_str ,
       function(responseData){   
          $("#save-result").empty().append(responseData); 
       }, 
       error: function() { 
            $("#save-result").append("An error occured during processing"); 
       }
   }); 

but all you really have to do is replace '[' & ']' back to themselves after serializing them. because serialize(); changed them to their htmlencoded value!

Neo
  • 11,078
  • 2
  • 68
  • 79
  • I didn't know the equivalent of [ and ] otherwize I would do it for you, just find out and use jQuery's .replace() function. – Neo Oct 10 '10 at 00:33