8

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?

B. Desai
16.4k5 gold badges28 silver badges48 bronze badges
asked Apr 23, 2017 at 10:43
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 Commented Apr 23, 2017 at 10:48

2 Answers 2

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

answered Apr 23, 2017 at 10:48
Sign up to request clarification or add additional context in comments.

1 Comment

this solution is what i was think about there is no need to convert array to string
5

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);
}}
?>
answered Apr 23, 2017 at 10:59

2 Comments

Thanks, the response in console is working, but how do I see if it printed to test.php without the page redirecting me to it?
You are welcome. If you want to print the value to test.php , then you dont need to use ajax. Just redirect with - var data = songList.join(','); window.location = "test.php?data="+data; And use explode() function on your php script to get back array from string.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.