0

I am trying to make a call (POST) whose url in XMLHttpRequest.open() and whose query in XMLHttpRequest.send() are variable depending of a condition.

So I have a select form:

<form id="myForm">
  <select name='options' id='options'>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
    <option>Another number</option>
  </select>
  <input type="submit">
</form>

The form after adding programatically a new field to create a new number if the option 'Another number' is chosen is:

<form>
  <select>
    <option></option>
    ...
  </select>
  <input type="text" name="ownOption" id="" ownOption> //New field in form created when 'Another number' is chosen.
  <input type="submit">
</form>

And the script is:

<script>
  var e = document.getElementById("options");
  var myQuery = ''
  var myUrl = 'firstUrl'
  e.addEventListener('change', function() {
      var index = e.selectedIndex;
      myQuery = e.options[index].text
      if (myQuery == 'Another number') {
        //Create new input field in form
        myUrl = 'secondUrl'
      } 
    })

    //Getting elements from new form after adding field programatically.
    var data = document.getElementById('myForm')

    //Listening to event and AJAX call
    data.addEventListener('submit', makeRequest);

    function makeRequest(e) {
      e.preventDefault();
      var xhr = new XMLHttpRequest()
      xhr.onreadystatechange = callback;
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.open('POST', myUrl, true); //myUrl is 'firstUrl' or 'secondUrl' depending if 'Another number' is chosen or not-That works well
      //I want to do something like below; that is, alternative queries depending of a condition. The code below doesn't work
      if (myQuery == 'Another number') {
        xhr.send('clicks=' + data.elements[1].value) //From the new input field, second in order in the form.
      } else /*myQuery is any of the options but the last*/ {
        xhr.send('clicks=' + myQuery)
      }
    })
</script>

How can I can do a alternative query in XMLHttpRequest.send(query) depending if there have been selected one of the given options or a new one through the new input field.

3
  • So the question is "How do I change the value of a variable based on user input"? Commented Jan 31, 2018 at 20:21
  • Your e.addEventListener function is missing a closing brace. Commented Jan 31, 2018 at 20:23
  • The question is if how can I do the XMLHttpRequest.send(query) variable. The form holds two elements: the first a HTML select, the second a HTML input. If any option of select but the last is chosen the query is based in the options. but if the last is chosen the second element form is created and the query is based in that second element. Commented Jan 31, 2018 at 20:42

1 Answer 1

1

First of all, you'll need a helper function to performs XMLHttpRequest properly in order to return data asynchronously. For example:

var newXHR = null; // Once initialized with the XMLHttpRequest object, you can use the abort() method from anywhere in the code.

function sendXHR(options, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(options.type, options.url, true);
  newXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  newXHR.send(options.data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response);
    }
  };
}

Usage:

sendXHR({
  url: myUrl,
  type: "POST",
  data: (myQuery === "Another number") ? "clicks=" + myForm.elements[1].value : "clicks=" + myQuery
}, function(response) {
  //console.log(response);
});

Something like this:

(function() {
  var newXHR = null; // Once initialized with the XMLHttpRequest object, you can use the abort() method from anywhere in the code.

  function sendXHR(options, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(options.type, options.url, true);
    newXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    newXHR.send(options.data);
    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response);
      }
    };
  }

  var myForm = document.getElementById("myForm"),
    options = document.getElementById("options"),
    myQuery = "",
    myUrl = "https://httpbin.org/post?page=firstUrl";

  options.onchange = function() {
    myQuery = this.options[this.selectedIndex].text;
    if (myQuery === "Another number") {
      myUrl = "https://httpbin.org/post?page=secondUrl";
    }
  };

  myForm.onsubmit = function(e) {
    e.preventDefault();

    sendXHR({
      url: myUrl,
      type: "POST",
      data: (myQuery === "Another number") ? "clicks=" + myForm.elements[1].value : "clicks=" + myQuery
    }, function(response) {
      //console.log(response);
    });
  }
}());
<form id="myForm">
  <select name='options' id='options'>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
    <option>Another number</option>
  </select>
  <input type="submit">
</form>

Hope this helps.

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

1 Comment

Yes, it works fine. Only I needed to change myQuery = this.options[this.selectedIndex].text; for myQuery = this.options[this.selectedIndex].value, putting a value attribute in the last option. For some reason it doesn't work with text but yes with value

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.