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.

0

3 Answers 3

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);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks alot for prompt answer :)
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 Agreed, I've changed it slightly to use the object notation, which will force jQuery to handle the URLencoding so that you can ignore
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}';

Comments

0

HI,

use json_encode() on parse_array.php

and retrive data with json_decode()

2 Comments

why would i encode the array in php? I want to use it in php.
yes i know how to send json back to jquery. and that was not my question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.