I am trying to set up a form to transfer data to my php file via forms filled out by the user. I want to create my own GET request so simplify it, but when i submit my form it is a different URL than the one i created.
I console logged my form.action and got (both fabricated data):
.../index.php?search1=987654321&search2=987654321
but the URL i got was (i inputted 987654321):
/index.php?search1=987654321
File: index.html
<form id="searchForm" action="/index.php" method="GET">
<input type="submit" value="Search" onclick="createActionGetRequest()">
<br><br>
<text id="search1Text">Social Security Number</text><input id="searchField1" type="text" name="search1"><br>
<text id="search2Text"></text>
</form>
File: helper-functions.js
function createActionGetRequest()
{
var form = document.getElementById("searchForm");
var elements = form.elements;
var values = [];
for (var i = 0; i < elements.length; i++)
{
values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));
}
var userForm = document.getElementById("userType");
values.push(encodeURIComponent("userType") + '=' + encodeURIComponent(userForm.value));
var searchForm = document.getElementById("searchType");
values.push(encodeURIComponent("searchType") + '=' + encodeURIComponent(searchForm.value));
// dummy test for GET request
form.action += '?' + "search1=987654321" + '&' + "search2=987654321";
console.log(form.action);
alert('pause');
form.submit();
}
When you click on a Submit button within a form, its always call form.submit()
by browser. Which mean 2 calls were made, /index.php?search1=987654321
made by browser and /index.php?search1=987654321&search2=987654321
by your js code
You can add event.preventDefault()
to createActionGetRequest()
to prevent the browser call.
function createActionGetRequest(event)
{
event.preventDefault()
...
}
The GET method also replace the request queries with the form input values. You can add another input instead of changing form.action.
var input = document.createElement("input");
input.type = "text";
input.name = "search2";
form.appendChild(input);