-1

This is what I have tried so far, but it doesn't seem to work.

      var myJSON = JSON.stringify(distMatrix);

      var testform = `<form id="jsform" action="test.php" >
        <input type="hidden" name="array" value="${myJSON}"> /
      </form>`

      var printdata = document.getElementById('jsform');
      document.write(printdata);
      document.getElementById('jsform').submit();
Clabis
  • 15
  • 2
  • 8

2 Answers2

0

You are trying to submit your form before it is actually created. First do document write and then submit.

UPD: ok, here we go.

  1. Create form by simply putting it to html part of your file.

  2. Set the required data into input via JS

  3. submit the form

var distMatrix = [[1,2],[2,2]];

// save the value into input
var input = document.getElementById('dist_matrix_json');
input.value = JSON.stringify(distMatrix);

// submit the form
document.getElementById('jsform').submit();
<form id="jsform" action="test.php" >
    <input type="hidden" id="dist_matrix_json" name="array" value=""> /
</form>
Denis O.
  • 1,841
  • 19
  • 37
  • 1
    it looks like they just are passing a json object, which would be just a simple XMLHttpRequest() routine and no html. – drtechno Sep 28 '19 at 12:51
  • @drtechno you're right and that is far not the only issue of the example. yet, to answer the question asked we only need to put submitting line at the end. – Denis O. Sep 28 '19 at 12:54
0

Sending a json object can be as simple as this javascript :

 <script>
 var myObj = { "name":"John", "age":31, "city":"New York" };
 var myJSON = JSON.stringify(myObj);
 window.location = "demo_json.php?x=" + myJSON;
 </script>

That was for the GET method.

if you need post or put methods:

    <div>
      <form id="myForm" action="page.php" method="post">
          <p id="demo"></p>
      </form>
    </div>

    <script>
     var myObj, x;
     myObj = {"name":"John", "age":30, "car":null};
     for (x in myObj) {
     document.getElementById("demo").innerHTML += '<input type="text" name="'+x+'" value="'+myObj[x]+'"><br>';
      }
      document.getElementById("myForm").submit();
     </script>
drtechno
  • 298
  • 2
  • 9