Sending JavaScript array to PHP via POST

I am trying to post 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:

Note: Undefined index: data p>

Why is the data variable irrelevant when trying to print or use it?

+3


source to share


3 answers


1) $ .post ('url') - The Ajax request is being made by the method $.post()

and you have specified "testing.php"

as a url which is invalid.

2) window.location = 'test.php' . This is used to redirect to a specific page and you are redirected to 'test.php'

without any parameters / data. This is why its showing "Note: Undefined index: data"



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

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

      

+3


source


This is not how POST request works. Learn more about Ajax, but for now, how should you 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);
?>
      

Run codeHide result


+5


source


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

      

-2


source







All Articles