How to parse HTML Form array and associative array in javascript for XMLHttpRequest

How to pass and process HTML Form array and associative array in javascript, so that the processed data can be posted through XMLHttpRequest to .php for further processing? Thanks!

Here is my semi pseudo code:

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>
<p id="result"></p>
 
<form onsubmit = "return process_array(this)">
<input type="text" name="array[]" value="a" /> 
<input type="text" name="array[]" value="b" /> 
<input type="text" name="array[]" value="c" /> 
<input type="number"  name="assoc_array['a']" value=1 />
<input type="number"  name="assoc_array['b']" value=2 />
<input type="number"  name="assoc_array['c']" value=3 />
<input type="submit" value = "process" />
</form >

<script>
function process_array(f) {
  var a=f.elements["array[]"]; //not working
  var b=f.elements["assoc_array[]"]; //not working
   
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "process.php", false);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("array=" +a+"&assoc_array =" + b); //working or not?
  return false;
}
</script>

</body>
</html>

process.php

<?php

        if(isset($_POST["array"]) && is_array($_POST["array"])){    
            foreach($_POST["array"] as $key => $value)
            {
              //processing array
            }
        }

    if(isset($_POST["assoc_array"]) && is_array($_POST["assoc_array"])){
        foreach($_POST["assoc_array"] as $key => $value){
            if(is_numeric($value)){
                //processing assoc_array
            }
        }
    }

echo result;
?>

var a=f.elements[“array”];

var b=f.elements[“assoc_array”];

These two lines do not work, result in undefined. and I am afraid that the following won’t work either.

xhttp.send(“array=” +a+“&assoc_array =” + b)

So, what is the correct coding? Thanks!

Gonna punt and go with… Dont? (okay, well, dont do it that way, anyway)

You might want to look at Using FormData Objects - Web APIs | MDN (mozilla.org), and not try to handle the individual fields.

Thanks, m_hutley. I will chect it out.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.