1

I am extending an internal web application project written with HTML, PHP and pure javascript. I want to POST a javascript integer array, alongside with other inputs, into another PHP file for further processing.

A very simplified version of what I would like to achieve is like this:

form.php

<form action="post.php" method="POST">
    <!-- along with other inputs -->
    <input type="hidden" id="ints" name="ints">
    <input type="submit" name="submit" id="submit" value="SUBMIT">
</form>
<script>
    var ints = [2,4,6];
    document.getElementsByName("ints").value=ints;
</script>

post.php

if (isset($_POST['ints'])){
    var_dump($_POST['ints']); //expected an array of numbers or strings
}else{
    echo "not POSTed";
}

But it seems that I failed to POST it. I have tried making the input field ints as ints[] and tried using getElementById. The best I have got is a string "2,4,6", and I may have done this using explode() in PHP, but I would like to know if there are better options.

I want to stick with pure javascript, but if it is not possible, I may try other stuffs like jQuery. Any hints and suggestions are appreciated.

3
  • 2
    Possible duplicate of Passing Array Using Html Form Hidden Element Commented Sep 13, 2017 at 10:24
  • you should not send array in input field. Send value with , comma separated Commented Sep 13, 2017 at 10:27
  • Not so much of duplicate. That link wants to post a PHP array in my understanding. W-well, I just want to know if there is a cleaner way to make this work, maybe... Commented Sep 14, 2017 at 1:43

2 Answers 2

1

Try replacing this:

document.getElementsByName("ints").value=ints;

... with this:

document.getElementsByName("ints")[0].setAttribute("value", ints);

There doesn't seem to be a value property on the node list returned by getElementsByName() which works the way you're trying to use it in your code above. Note that if the correct element isn't the first (maybe only) match for getElementsByName(), you'll have to change the index above, or use another means of selecting the element, like a class.

Sign up to request clarification or add additional context in comments.

Comments

0

The value in the input is string. you should pass the ints array using a serialized JSON array using either ajax or XmlHttpRequest (better)

submit.onclick = function(){

   ints = [1,2,3];

   var request = new XMLHttpRequest();

   request.open('POST', '/my/url', true);

   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

   request.send({
      ints : ints
   });

}

Comments

Your Answer

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.