user892134
user892134

Reputation: 3224

Send array from jQuery(ajax) to PHP

class email is an array of email addresses. How do i get the array in jQuery and then send the data with AJAX to send.php along with class title and message?

    <input type='text' size='30' class='email' value='[email protected]' />
    <input type='text' size='30' class='email' value='[email protected]' />
    <input type='text' size='30' class='email' value='[email protected]' />
    <input type='text' size='30' class='title' value='testing title' />
    <input type='text' size='30' class='message' value='testing message' />

<script type="text/javascript">
$(function() {
var title = $('.title').val();
var message = $('.message').val();

var dataString = 'title=' + title + '&message=' + message;
$.ajax({
    type: "POST",
    url: "send.php",
    data: dataString,
success:function () {


}

});
});
</script>

send.php

<?php


  $email = $_POST['email'];
  $title = $_POST['title'];
  $message = $_POST['message'];

foreach($email as $value) {

//send email

}
?>

Upvotes: 0

Views: 510

Answers (3)

Eric
Eric

Reputation: 97565

You can do it more simply that Felix King's answer, using serialize(), if you name your inputs:

<form id="the-form">
    <input type='email' size='30' name="email[]" value='[email protected]' />
    <input type='email' size='30' name="email[]" value='[email protected]' />
    <input type='email' size='30' name="email[]" value='[email protected]' />
    <input type='text' size='30' name='title' value='testing title' />
    <input type='text' size='30' name='message' value='testing message' />
</form>
$.ajax({
    type: "POST",
    url: "send.php",
    data: $("#the-form").serialize(),
    success: function() {

    }
});

Upvotes: 1

user1012851
user1012851

Reputation:

Won't this work?:

var datastring = $('#yourform').serialize();

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816272

This should do it:

var data = {
    title: $('.title').val(),
    message: $('.message').val(),
    email: $('.email').map(function(){ return $(this).val(); }).get()
};

$.ajax({
    type: "POST",
    url: "send.php",
    data: data,
    success:function () {

    }
});

data.email will contain an array of email addresses. jQuery takes care to encode the data properly. See jQuery.param.

Upvotes: 1

Related Questions