0

One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form. What I am doing wrong?

<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
    postcmd.push({"key": ele.id, "value": ele.value});
    for (key in postcmd) {
      if (postcmd.hasOwnProperty(key)) {
        console.log(postcmd[key])
      } 
    }

    request = $.ajax({
        url: "/index.php",
        type: "post",
        data: postcmd
    });

} 
</script>

Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?

    <?php
// index.php
?>

<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({ 
       type: "POST", 
       url: "index.php", 
       data: { testArray : arrayfromjs}, 
       success: function() { 
              alert("Success"); 
        } 
}); 
</script>

</head>
<body>

<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);

?>
</body>
</html>
mfuerli
  • 44
  • 7

3 Answers3

0

Per the jQuery documentation,

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.

If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.

kzhao14
  • 2,470
  • 14
  • 21
  • Using my original script the console output is: {key: "4@@@expensetype", value: "fuel"}. However $_POST("postcmd") stays empty after submitting the FORM. I was hoping to get an array here. And the output of $_POST delivers the whole table transferred by the FORM. But the intention of using javascript is to reduce the later in PHP/SQL to be written table-fields to only the changed table-fields. The array built in javascript "key=ele.id:value=ele.value" comes from onchange elements at the INPUT boxes of the FORM. – mfuerli Apr 14 '20 at 23:38
0

You are creating the following structure using the push method:

[
  {
     "key":"first_name",
     "value": "Bob"
  }
]

Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".

function formsubmitplus(ele) {
    postcmd.push({"key": ele.id, "value": ele.value});
     for (key in postcmd) {
      if (postcmd[key].hasOwnProperty("key")) {
        console.log(postcmd[key].key)
      } 
    }

    request = $.ajax({
        url: "/index.php",
        type: "post",
        data: postcmd[0]
    });

} 

Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob

On the PHP side you should be able to grab those values as such:

<?php

echo $_POST['key'].PHP_EOL;
echo $_POST['value'];

?>

Alternative Method - JSON Submission

You could make the following modification to post the data as JSON:

function formsubmitplus(ele) {
    for (key in postcmd) {
      if (postcmd[key].hasOwnProperty("key")) {
        console.log(postcmd[key].key)
      } 
    }

    request = $.ajax({
        url: "/index.php",
        type: "post",
        contentType: 'application/json',
        data: JSON.stringify(postcmd)
    });

} 

Then on the PHP side you can grab the POST body using the following:

<?php
    echo "<pre>";
    $json_data = json_decode(file_get_contents('php://input'), true);
    print_r($json_data);
?>

If you would rather work with a PHP Object vs an Associative array. Just change true to false.

  • In this case the key is also variable - depending on the line number (before the @@@) of a huge table. So no hardcoded echo $_POST['key'] can be used. The console delivers: {key: "1@@@expensetype", value: "entertainment"} or {key: "2@@@invoicecurrency", value: "US$"} . The so achieved array (stored in postcmd) will be "exploded" later in PHP for further processing. But how to get this js-array from javascript to PHP? – mfuerli Apr 14 '20 at 23:54
0

Ad the end I found a solution without jquery which works for me the best. It is "playing" with HIDDEN form fields. Maybe someone finds it helpful:

function submitform() {
    Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
    var outarrayoutput = val + ' ==== ' + postcmd[val];
    console.log(outarrayoutput);
    var newHidInp = document.createElement('input');
    newHidInp.type  = 'hidden';
    newHidInp.name  = 'outArray[]';
    newHidInp.value = outarrayoutput;
    maintable.appendChild(newHidInp);
}); 
    document.maintable.submit();
}
mfuerli
  • 44
  • 7