I am trying to make a ajaxcall (POST) whose url in XMLHttpRequest.open() and whose query in XMLHttpRequest.send() are variable depending of a condition.
So I have a htmlselect 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.