Sending an array in php from JavaScript / jQuery

Possible duplicate:
send data arrays from php to javascript

I know that there are many such questions, but I believe that none of them is so clear.

I have an Ajax request, for example:

$.ajax({
    type: "POST",
    url: "parse_array.php",
    data: "array=" + array,
    dataType: "json",
    success: function(data) {
        alert(data.reply);
    }
});

How can I send a JavaScript array to a php file, and what does php look like that parses it into a php array?

I am using JSON.

+3
source share
3 answers

Step 1

$.ajax({
    type: "POST",
    url: "parse_array.php",
    data:{ array : JSON.stringify(array) },
    dataType: "json",
    success: function(data) {
        alert(data.reply);
    }
});

Step 2

The php file is as follows:

<?php 



  $array = json_decode($_POST['array']);
    print_r($array); //for debugging purposes only

     $response = array();
     if(isset($array[$blah])) 
        $response['reply']="Success";
    else 
        $response['reply']="Failure";

   echo json_encode($response);

Step 3

Success function

success: function(data) {
        console.log(data.reply);
        alert(data.reply);
    }
+8
source

You can just pass a javascript object.

JS:

var array = [1,2,3];
$.ajax({
    type: "POST",
    url: "parse_array.php",
    data: {"myarray": array, 'anotherarray': array2},
    dataType: "json",
    success: function(data) {
        alert(data.reply); // displays '1' with PHP from below
    }
});

On the php side, you need to print the JSON code:

PHP:

$array = $_POST['myarray'];
print '{"reply": 1}';
+1
source

HI,

json_encode() parse_array.php

json_decode()

0

All Articles