0

I have:

...
<script>
function test(){
    var pageName="TestArray.php";
    var text="numbers";
    var array=['one','two'];
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    };
    xmlhttp.open("GET", pageName+"?text="+text+"&array[]=["+array+"]");
    xmlhttp.send();
 }
 test();

</script>
...

In TestArray.php,

<?php
    $response="";
    $numbers="";
    if(isset($_GET["text"])){
        $numbers=$_GET["text"];
        $response="numbers=".$numbers."&";
    }
    if(!empty($_GET["array"])){
        foreach($_GET["array"] as $checkedItem){
            $response.=$checkedItem."&";
        }
        $response=substr($response,0,strlen($response)-1);
    }
    echo $response;
?>

It should alert 'numbers=numbers&one&two'. How to make foreach($_GET["array"]){...} work by deciding what to write after text="+text+ ?

3
  • You can pass array into a querystring but not like this. I would need to be like ?array[]=this&array[]=is&array[]=test Commented May 10, 2017 at 23:12
  • Even that returns 500 (Internal Server Error). Commented May 10, 2017 at 23:25
  • That usually means a syntax error in the PHP script. Check the server error log for the details. Commented May 10, 2017 at 23:28

2 Answers 2

1

As the previous answer states, you will need to parameterize the array into a url string.

If you will have to repeatedly create url strings you could use a function to convert an object to a URL parameter string.

const es6parameterize = obj => 
  Object.keys(obj).map(k => 
    Array.isArray(obj[k]) 
      ? obj[k].map(x => `${k}[]=${x}`).join('&')
      : `${k}=${obj[k]}`
  ).join('&')


function es5parameterize(obj) {
  var ret = []
  for (var k in obj) {
    if (obj[k].constructor === Array) {
      [].push.apply(ret, obj[k].map(function(x) { return k + '[]=' + x }))
    }
    else {
      ret.push(k + '=' + obj[k])
    }
  }
  return ret.join('&')
}

console.log(
  "pageName?" + es6parameterize({ text: 'foo', array: ['bar', 'baz'] })
)

console.log(
  "pageName?" + es5parameterize({ text: 'foo', array: ['bar', 'baz'] })
)

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

Comments

0

You should change this

  xmlhttp.open("GET", pageName+"?text="+text+"&array[]=["+array+"]");

To this:

xmlhttp.open("GET", pageName+"?text="+text+"&array[]="+array[0]+"&array[]="+array [1]);

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.