0

I am trying to send this array from javascript to PHP, but I keep getting Undefined index: list in on line 3. This error is coming from in the php file.

I am going to provide to whole code including the html, javascript, and php.

Here is the HTML code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type= "text/javascript" src = "js.js"></script>
</head>
<body>
    <form class = "wall" action="phpf.php"  method="post">
        <label>What is your name</label>
        <input type="text" name ="name" />

        <input type = "submit"  value = "Submit Order" />
    </form>
</body>

Here is the Javascript code

$(document).ready(function () {

var list = [34, 56, 23, 90, 43, 58];
$.ajax({
    type: "POST",
    url: "phpf.php",
    data: {'list': JSON.stringify(list)},
    cache: false,
    success: function (response) {
        console.log("This is the list", list);
    }

});
})

Here is where I am receiving it in PHP

<?php

$list = json_decode($_POST['list']);

echo "This is the new list".$list;
?>

I was hooping that someone could me please.

Ahamed
  • 59
  • 3
  • 9
  • `json_decode()` creates an object which will usually throw an error if you try to echo it. Have you watched the AJAX request / response in the browser's developer tools? Are there any errors reported? Are you running this on a web-server? – Jay Blanchard Jan 26 '17 at 18:32
  • When you echo the $list, you give variable name, not array index, try something like $list[0] or better, just do print_r($list); –  Jan 26 '17 at 18:32
  • I found this answer here maybe can help you. http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php – Thomaz Lima Jan 26 '17 at 18:49

1 Answers1

0

You can't print an array using echo, you should use print or var_dump in your php file:

<?php

$list = json_decode($_POST['list']);

echo "This is the new list";
print_r($list);

i've verified and it's working, i just add jquery, i suppose you are loading the file in js.js. But i put my code right here:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>

<script type= "text/javascript" src = "https://code.jquery.com/jquery-2.2.4.js"></script>

</head>
<body>
<form class = "wall" action="phpf.php"  method="post">
    <label>What is your name</label>
    <input type="text" name ="name" />

    <input type = "submit"  value = "Submit Order" />
</form>
</body>

<script>
$(document).ready(function() {
   var list = [34, 56, 23, 90, 43, 58];
   $.ajax({
    type: "POST",
    url: "phpf.php",
    data: {'list': JSON.stringify(list)},
    cache: false,
    success: function (response) {
        console.log("This is the list", list);
    }

  });
});
</script>
</html>
migueref
  • 302
  • 1
  • 7