-1

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

Can I pass an array to a php file through JavaScript using AJAX? In my application code JavaScript builds the parameters based on user input, and then an AJAX call is made to a processing script.

For example, if the processing script url was process_this.php the call made from JavaScript would be process_this.php?handler=some_handler&param1=p1&param2=p2&param3=p3

Could I do something like this?:

process_this.php?handler=some_handler&param1=[array]

Thanks.

Community
  • 1
  • 1
Anonymous
  • 1
  • 1

4 Answers4

2

using JQUERY you could do something like this

<script language="javascript" type="text/javascript">
$(document).ready(function() {

    var jsarr = new Array('param1', 'param2', 'param3');

    $.post("process_this.php", { params: jsarr}, function(data) {
        alert(data);
    });

});
</script>

php script

<?php print_r($_POST['params']); ?>

output would be

Array ( [0] => param1 [1] => param2 [2] => param3 )

Clint C.
  • 678
  • 13
  • 31
0

What about sending an JSON Object via Post to your PHP-Script? Have a look at this PHP JSON Functions

develop-me
  • 24
  • 4
0

You can use JSON to encode the array to a string, send the string via HTTP request to PHP, and decode it there. You can do it also with objects.

In Javascript you do:

var my_array = [p1, p2, p3]; 
var my_object = {"param1": p1, "param2": p2, "param3": p3};
var json_array = JSON.stringify(my_array);    
var json_object = JSON.stringify(my_object);    
var URL = "process_this.php?handler=some_handler" +
          "&my_array=" + json_array + "&my_object=" + json_object; 

In PHP you do:

$my_array = json_decode($_POST['my_array'])); 
$my_object = json_decode($_POST['my_object'])); 
Jiri Kriz
  • 9,192
  • 3
  • 29
  • 36
0

You can send a json object to your php , thats the standard approach

dusual
  • 2,097
  • 3
  • 19
  • 26