42

How can I pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

Please show an example of code that would do the trick.

Thanks!

PleaseHelpMe
  • 709
  • 3
  • 8
  • 13

4 Answers4

64

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});
Grant
  • 11,799
  • 13
  • 42
  • 47
prodigitalson
  • 60,050
  • 10
  • 100
  • 114
25

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Groovetrain
  • 3,315
  • 19
  • 23
8

Here it goes an example:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

Rui
  • 516
  • 3
  • 8
  • 1
    But what if the array is in a Javascript variable? – PleaseHelpMe Apr 06 '11 at 19:20
  • 6
    var choices = ["Jon", "Susan"]; $.post("test.php", { 'choices[]': choices }); – Rui Apr 06 '11 at 19:25
  • @Rui, why is the single quotation around `choices[]` ? where is the rule about it in the site of the js or jquery authority please ? – Istiaque Ahmed Nov 02 '12 at 06:50
  • when i was sending `var choiseArr=[];choiseArr=[0]='Jon'; choiseArr=[1]='Susan'; $.post("test.php", { 'choices': choiseArr }); it sends request but not as an array but as choices two times. so i was getting value susan only. your answer helped. saved lots of time.. thanks... :) – Ravikumar Sharma Nov 14 '13 at 07:20
1

I think we should sent in this format

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

It worked for me

Community
  • 1
  • 1
Sahithi
  • 83
  • 10