Skip to content Skip to sidebar Skip to footer

Javascript Array To Php With Jquery Ajax

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.

Solution 1:

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">
    <inputtype="text" name="service[0]" value="1st Service" />
    <inputtype="text" name="service[1]" value="2nd Service" />
    <inputtype="text" name="service[2]" value="3rd Service" />
    <inputtype="text" name="service[..]" value=".. Service" />
    <inputtype="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.

Solution 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

Solution 3:

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 valuesvar values = [];
    $.map($inputs, function(e) {
        values.push(e.value);
    });
    event.preventDefault();
});

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

Post a Comment for "Javascript Array To Php With Jquery Ajax"