Pass PHP Array via jQuery Ajax

15,289

Solution 1

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

Solution 2

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

Share:
15,289
Dodinas
Author by

Dodinas

Updated on July 24, 2022

Comments

  • Dodinas
    Dodinas almost 2 years

    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!