0

Possible Duplicate:
Passing JavaScript Array To PHP Through JQuery $.ajax

I'm trying to pass some variables gathered from n dynamically generated inputs to php with ajax.

<input type="text" class="big" id="service" name="service[]" maxlenght="100"/>

This is the dynamically generated input(there could be 1 or 100). Now, if I submit them without ajax it gives me an array in php by simply doing

$services = $_POST['service'];

But what if I want to do it with ajax without refreshing the page?

var action = $("form_act").attr('action');
var form_data = {
    service: $("#service").val(),
    ajax_request: 1
};
$.ajax({
    type: "POST",
    url: action,
    data: form_data,
    dataType: "json",
    success: function (response) {
        if (response.error == 'none')
            $("#form_content").slideToggle('slow', function () {
                $('#form_content').load('includes/db_setup_form.php');
                $("#form_content").delay(500).slideToggle('slow');
            });
        else {

            $("#ajax_response").html("<p>" + response.msg + "</p>");

        }
    }
});

It only sends the first service variable and not a complete array with the others(if there are) variables. Any suggestions?

Community
  • 1
  • 1
g0dl3ss
  • 393
  • 1
  • 6
  • 19
  • already read that but i'm not sure on how to proceed on this case since i've more than 1 variable to send(in the above code i only included the array i need to pass, but i've more inputs to send). – g0dl3ss Jan 02 '12 at 08:42
  • This should be helpful as well: http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery – Geert Jan 02 '12 at 08:47

3 Answers3

3

you problem that selector ('#services') takes only first input value. You should remove id and just serialize form as below.

If all you need to pass is all values from form you can use

data: $('form#my-form').serialize() // this code puts all of the inputs into passable and readable for PHP, way.

And then in $_POST['service'] will be an array of inputs values.

For example:

<form action="save.php" method="post" id="services">
    <input type="text" name="service[0]" value="1st Service" />
    <input type="text" name="service[1]" value="2nd Service" />
    <input type="text" name="service[2]" value="3rd Service" />
    <input type="text" name="service[..]" value=".. Service" />
    <input type="text" name="service[N]" value="N Service" />
</form>

In your JS:

$.post($('form#services').attr('action'), $('form#services').serialize(), function(response) {});

And then in save.php you can get an array in $_POST:

var_dump($_POST['service']);

Hope that's is exactly what you need.

devdRew
  • 4,393
  • 3
  • 24
  • 33
  • What if i'd like to send another variable(ajax_request) together with those from the form? Thanks – g0dl3ss Jan 03 '12 at 10:26
  • Tried `data: $('form#invoice_form').serialize(), ajax_request:1,` but it didn't work – g0dl3ss Jan 03 '12 at 11:02
  • $('form#invoice_form').serialize() + '&ajax_request=1'; Maybe...) .serialize() return url-encoded string, so you can append pairs key-value to this string by adding &key=value. – devdRew Jan 03 '12 at 11:12
2

You should select the inputs by name attribute because it is invalid to have more than one element with the same ID in an HTML document. Your jQuery selector knows it's looking for what should be a unique element so it stops after it finds the first one. Also the .val() function only finds the value of the first element in the set of elements selected.

Here is what I would change:

var form_data = {
    service: $("#service").val(),
    ajax_request: 1
   };

To:

var form_data = {
    service: $('[name="service[]"]').serialize(),
    ajax_request: 1
   };

Here is a demo: http://jsfiddle.net/sS7YP/

Here is the documentation for .serialize(): http://api.jquery.com/serialize

Jasper
  • 75,717
  • 14
  • 151
  • 146
2

A solution which creates a clean array of the values of your service[] inputs, using jQuery.map().

var $form = $('#form_id'),
    $inputs = $form.find('input[name^=service]'); // Do not select by ID

$form.on('submit', function(event) {
    // Build an array only containing the services values
    var values = [];
    $.map($inputs, function(e) {
        values.push(e.value);
    });
    event.preventDefault();
});

http://jsfiddle.net/eTU2y/1/

Geert
  • 1,804
  • 15
  • 15