Christian Wibowo
Christian Wibowo

Reputation: 225

parsing array from ajax into php

i want to pass array which is generated by javascript..just say i have an array named vals2=('john','peter') and i want to pass this array to my php page(insert_paket_f.php).

this is my ajax code :

$.ajax({
        type: "POST",
        url: "insert_paket_f.php",
        data: { data : vals2 },
        cache: false,
        //vals=('john','peter','andrea');
        success: function(){
            alert("OK");
        }
    });

insert_paket_f.php

$data1 = $_POST['data'];                
$data1 = explode(",", $_POST['data']);
print_r($data1);

when i run my browser, its show empty array, and just looks like this Array ( [0] => )

how can i fix this?

thanks..

Upvotes: 1

Views: 700

Answers (3)

suiz
suiz

Reputation: 377

In the Data Feild try to use variables

as echo data: data[]=john&data[]=peter&data[]=andrea

Code:-

$.ajax({
    type: "POST",
    url: "insert_paket_f.php",
    data: "data[]=john&data[]=peter&data[]=andrea",
    cache: false,
    success: function(){
        alert("OK");
    }
});

Is It working?

Upvotes: 0

web-nomad
web-nomad

Reputation: 6003

Try this:

Use join to send the javascript array as an string.

Javascript

var vals2 = ['john','peter'];
$.ajax({
    type: "POST",
    url: "insert_paket_f.php",
    data: { data : vals2.join(',') },
    cache: false,
    success: function(){
        alert("OK");
    }
});

PHP

$data1 = $_POST['data'];                
$data1 = explode(",", $_POST['data']);
print_r($data1);

Hope it helps.

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

Try:

$data1 = json_decode($_POST['data']);
print_r($data1);

Upvotes: 0

Related Questions