tags:

views:

28364

answers:

13

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.

+1  A: 

Square brackets are not allowed as name or id parameter values. Further id values must be unique throughout the HTML document.

Your PHP code produces HTML that violates both of these rules. I guess your problems are a result of this.

Try this, and the try jQuery again:

$i = 0;
while ($row = mysqli_fetch_assoc($result))
{
  $i++;
  extract($row);
  echo "<tr>";
  echo "<td bgcolor='#FFFFFF'><input id='bookArray_$i' "
      ."name='bookArray' type='checkbox' value='$book_id' />$book_id</td>";
  echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
  echo "</tr>";
} // while
Tomalak
A: 

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
I think that the serialize(), when applied to a wrapped set from a form, returns a properly encoded string.
kgiannakakis
Yeah. Just tested it. Fixed.
tvanfosson
I'm unsure it the selector is optimal. Shouldn't it be either just "form" or "#bookform"? I thought using just "#id" was faster but otherwise equivalent to "element#id".
Tomalak
Oh, and there's a surplus semi-colon at the end of your code. Just delete that comment after you fixed it.
Tomalak
A: 

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?

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
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
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
@Tomalak: `varname[]` is needed for PHP to handle groups of checkboxes (or any inputs for that matter) as an array server side.
nikc
A: 

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 += " } });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
+6  A: 

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

Good idea, except it should be serialize().replace(/%5B%5D/g, '[]');
postalservice14
(Because, if it's not a regular expression with the global property, only the 1st match is replaced.)
JKS
A: 

I am just facing the same problem now

Seems the problem of serializing array fields cannot be solved then.

you need to replace '[' and ']' individually and for every match.
Neo
+1  A: 

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
+1  A: 

@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.

Delazee
A: 

i have the same problem in my project. i see that some of you don't get even what is jquery and php :) wtf?? php has nothing to do with it.

distances
+1  A: 
var data = $(form).serialize();
$.post('post.php', '&'+data);
FDisk
+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
+1  A: 

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)
       {

       }
});
Gafitescu Daniel
A: 

jQuery 1.4

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

decodeURIComponent(myform);
Philo
A: 

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
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