Sending an array to php from JavaScript/jQuery

11,298

Solution 1

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);
    }

Solution 2

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:
11,298
FraserK
Author by

FraserK

I'm a keen coder and learner :)

Updated on June 30, 2022

Comments

  • FraserK
    FraserK almost 2 years

    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.