1

I have some PHP code that posts data to an API, and compiles the POST information for curl as follows:

<?php
$post_data['field'] = 'fieldsValue';
$post_data['field2'] = 'field2sValue';
$post_data['parameters']['limit'] = '10';
$post_data['parameters']['offset'] = '10';
$post_data['parameters']['search'] = 'value';
?>

How would one achieve the same nested parameters to accommodate ['parameters']['limit'] and ['parameters']['offset'] values in a javascript post using XMLHttpRequest?

Code so far:

<script>
function fieldSearch(query){
    var xhttp = new XMLHttpRequest();
    var postdata = "field=fieldsvalue&field2=field2sValue";
    xhttp.open("POST", "app.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.setRequestHeader("Content-length", postdata.length);
    xhttp.send(postdata);
}
</script>
2
  • 1
    are you saying you want the post variable to be like this $_POST['parameters']['limit'] ? Commented Jan 19, 2016 at 8:18
  • Yes. I am trying to notate my objects so that they are in nested keyed arrays... essentially. Commented Jan 19, 2016 at 8:26

1 Answer 1

1

try create this.

<!DOCTYPE html>
<html>
<head>
    <title></title>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
      <script type="text/javascript">

          function formSubmit(frmElement){
            var xhr = new XMLHttpRequest();
            xhr.onload = function(){alert(xhr.responseText);}
            xhr.open(frmElement.method, frmElement.action,true);
            xhr.send(new FormData(frmElement));
            return false;
          }
      </script>

</head>
<body>

<form method="post" action="app.php" onsubmit="return formSubmit(this);">
    <input type="text" name="field"/>
    <input type="text" name="field2"/>
    <input type="text" name="parameters[limit]"/>
    <input type="text" name="parameters[offset]"/>
    <input type="text" name="parameters[search]"/>

    <input type="submit" value="submit">
</form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

that works. I can just hide forms as needed. thanks!

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.