简体   繁体   中英

Sending a JavaScript array to PHP via POST

I am trying to send a JavaScript array to a PHP file via POST.

JS:

var songlist = ['song1', 'song2', 'song3'];

var sendData = function(){
    var data = songList.join(',')
    $.post('test.php', {data: data}).always(function() {
        window.location = 'test.php';
    });
}
sendData();

test.php:

<?php
$songData = $_POST['data'];
$songData = explode(',', $songData); 
print_r(array_values($songData));
?>

when sendData(); directs me to test.php I get:

Notice: Undefined index: data

Why doesn't the data variable have any value when I try to print or use it?

That's not how POST request works. Read more about Ajax, but for now, that's how you should do it.

 var songlist = ['song1', 'song2', 'song3']; var sendData = function() { $.post('test.php', { data: songlist }, function(response) { console.log(response); }); } sendData(); 
 // test.php <?php $songData = $_POST['data']; print_r($songData); ?> 

1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.

2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"

3) Try to understand how ajax works. Follow it -

var songlist = ['song1', 'song2', 'song3'];

var sendData = function() {
  $.post('test.php', {
    data: songlist
  }, function(response) {
    console.log(response);
  });
}
sendData();
// test.php
<?php
if(isset($_POST)){
    if(isset($_POST['data'])){
    $songData = $_POST['data'];
    print_r($songData);
}}
?>
var songlist = ['song1', 'song2', 'song3'];
var sendData = function(){
var data = songList.join(',')
$.post('testing.php', {data:     data}).always(function() {
window.location = "test.php?data=$data";
});
}
sendData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM