John Chase
John Chase

Reputation: 11

Dynamic Form Action URL

I'm trying to create a form on my website where a user has a text field that they can use to enter a registration number. I want the registration number to be added to the end of the action URL so when that page loads I can use PHP to explode the URL and grab the number. Here's an example of what I'm looking for...

<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>

Is it possible to take whatever is entered into the text field called registrationnumber and have it passed to the URL the form directs to? Maybe an easier way is to create a text field that has a button, when the button is clicked the URL is links to is dynamically created by adding the registrationnumber to the end.

Anyone know of a way to do this?

Upvotes: 0

Views: 220

Answers (1)

Ivan
Ivan

Reputation: 40618

Indeed you don't need a form to make an AJAX call. A simple input and button will suffice.

I have made a function that will make AJAX call, it will convert the object params containing all key/value pairs of the parameters you want to send to PHP, and concatenates it into a URL string:

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      callback(xmlhttp.responseText);
    }
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

Assuming you have an input field:

<input id="code" type="text">
<button id="sendData">Send</button>

Here's how we can use the function ajax:

function sendData() {

  parameters = {
    inputValue: document.querySelector('#code').value
  };

  ajax('target.php', parameters, function(response) {
    // add here the code to be executed when data comes back to client side      
    // e.g. console.log(response) will show the AJAX response in the console
  });

}

You can then attach the button to sendData using an event listener:

document.querySelector('#sendData').addEventListener('click', sendData)

Upvotes: 1

Related Questions