Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

marked as duplicate by Fraser, false, yanchenko, InfantPro'Aravind', Graviton Jan 3 at 3:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

up vote 5 down vote accepted

Step 1

"array=" + JSON.stringify(array)

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);
    }
share|improve this answer
Thanks alot for prompt answer :) – FraserK Mar 10 '11 at 4: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 5:39

HI,

use json_encode() on parse_array.php

and retrive data with json_decode()

share|improve this answer
why would i encode the array in php? I want to use it in php. – FraserK Mar 10 '11 at 4:42
bcoz your dataType is json – diEcho Mar 10 '11 at 4:44
yes i know how to send json back to jquery. and that was not my question. – FraserK Mar 10 '11 at 4:51

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}';
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.