tags:

views:

3987

answers:

4

Hello all,

I've got a php array:

$toField = explode(",", $ids);  //Which looks something like '24,25,26,29'

I want to pass this array via jQuery AJAX, with this:

<form id="myForm">
  <input type="hidden"  value="'.$toField.'">
  <input type="submit" id="sendMessage" class="faceboxSubmit" name="ok" value="Send Reply"/>
</form>

And here's my jQuery:

$("#sendMessage").click(function(event){
 event.preventDefault();
 var senderID = <?php echo $usrID; ?>;
 var receiverID = $("#toField").val();
 $.ajax( 
{ 
    type: "POST", 
    url: "replyMessage.php", 
    data: "senderID=" + senderID + "&subject=" + subject + "&message=" + message + "&receiverID=" + receiverID + "&threadID=" + thread_id,
 beforeSend: function() {
  $("#sendingMessage").show();
  },
            success: function() {
  alert("Success");
  }

         });    
 });

How can I pass the array, so that with the "replyMessage.php" page, I could take each ID from the Array, to do something like this:

    <?php 

    foreach ($_POST['receiverID'] as $receiverID) 
   { 
     mysql_query //etc...
   }

Any help is greatly appreciated!

A: 

you can get the string in the php code and separate it on the comma, then loop through the values.

http://us3.php.net/split

John Boker
+1  A: 

Hi,

First, you probably want to use implode, and not explode, to construct your $toField variable ;-)

$ids = array(24, 25, 26, 29);
$toField = implode(',', $ids);
var_dump($toField);

Which would give you

string '24,25,26,29' (length=11)

You then inject this in the form ; something like this would probably do :

<input type="hidden"  value="<?php echo $toField; ?>">

(Chech the HTML source of your form, to be sure ;-) )


Then, on the PHP script that receives the data from the form when it's been submitted, you'd use explode to extract the data as an array, from the string :

foreach (explode(',', $_POST['receiverID']) as $receiverID) {
    var_dump($receiverID);
}

Which will get you :

string '24' (length=2)
string '25' (length=2)
string '26' (length=2)
string '29' (length=2)

And, now, you can use thoses ids...

Pascal MARTIN
Exactly what I was looking for--thanks.
Dodinas
You're welcome :-) Have fun!
Pascal MARTIN
A: 

Few things going on I'd sort out:-

  • You're missing the id 'toField' on your toField input element.

  • You should be using implode() on the $id variable rather than exploding it.

  • On the otherside you should be calling explode() on the recieverId string.

Gavin Gilmour
+1  A: 
<form id='myform'>
 <input type='hidden' name='to[]' value='1' />
 <input type='hidden' name='to[]' value='2' />

 .. etc ..
 .. rest of you're form ..
</form>

jQuery change the data: .. part to:

data: $('#myform').serialize()

Then in you're PHP:

foreach ( $_POST [ 'to' ] as $num )
{
 // do something with $num;
}

Something like this an option?

Stefan