3

Possible Duplicate:
send arrays of data from php to javascript

I know there are many questions like this but I find that none of them are that clear.

I have an Ajax request like so:

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

How would I send a JavaScript array to a php file and what would be the php that parses it into a php array look like?

I am using JSON.

Community
  • 1
  • 1
FraserK
  • 304
  • 1
  • 3
  • 17

3 Answers3

9

Step 1

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

Step 2

You php file looks like this:

<?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

The success function

success: function(data) {
        console.log(data.reply);
        alert(data.reply);
    }
Jason
  • 15,064
  • 15
  • 65
  • 105
  • Thanks alot for prompt answer :) – FraserK Mar 10 '11 at 04:52
  • You'd want to URL-encode the result from `JSON.stringify`, i'd think, so a stray `&` in one of your object's strings wouldn't cut your string off prematurely and break your JSON. – cHao Mar 10 '11 at 05:39
  • @cHao Agreed, I've changed it slightly to use the object notation, which will force jQuery to handle the URLencoding so that you can ignore – Jason Dec 19 '13 at 04:19
1

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 JSON code:

PHP:

$array = $_POST['myarray'];
print '{"reply": 1}';
coldfix
  • 6,604
  • 3
  • 40
  • 50
0

HI,

use json_encode() on parse_array.php

and retrive data with json_decode()

xkeshav
  • 53,360
  • 44
  • 177
  • 245