最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sending a JavaScript array to PHP via POST - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Mar 7, 2018 at 11:47 B. Desai 16.4k5 gold badges28 silver badges47 bronze badges asked Apr 23, 2017 at 10:43 Damien StewartDamien Stewart 1531 gold badge1 silver badge10 bronze badges 1
  • I am not sure, but try use $_POST->data. Maybe this is object, becouse you send it to your script like object, no array – kalit Commented Apr 23, 2017 at 10:48
Add a comment  | 

2 Answers 2

Reset to default 8

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);
}}
?>
发布评论

评论列表(0)

  1. 暂无评论