Modifying the URL of an AJAX call prior to sending

I am looking to dynamically insert the data entered in a text box labeled 'postcode' into the URL parameters 'VALUE1' and 'VALUE2'. Unfortunately, I lack examples to provide as I am unsure of where to begin.

<input type="text" name="postcode" placeholder="Postcode" ><br>
<button type="button" onclick="loadDoc()">Get Postcode</button>

<p id="Addresses">No Postcode</p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("Addresses").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "https://api.getaddress.io/v2/uk/VALUE1&VALUE2", true);
  xhttp.send();
}
</script>

My query is

Answer №1

To improve your code, consider implementing encodeURI and adding input validation before making the API call. Take a look at this demo on https://jsfiddle.net/

<input id="text-box1" type="text" name="postcode" placeholder="Enter Postcode" ><br>
<input id="text-box2" type="text" name="postcode" placeholder="Enter Second Postcode" ><br>
<button type="button" onclick="loadDoc()">Fetch Postcodes</button>

<p id="Addresses">No Postcodes Found</p>

<script>
function loadDoc() {
 var val = document.getElementById("text-box1").value;
 var val2 = document.getElementById("text-box2").value;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("Addresses").innerHTML = xhttp.responseText;
    }
  };
  var uri = encodeURI("https://api.getaddress.io/v2/uk/"+val+"&"+val2);
  console.log(uri);
  xhttp.open("GET", uri, true);
  xhttp.send();
}
</script>

Answer №2

Here are some steps to consider:

<input type="text" name="zipcode" placeholder="Zip Code" ><br>
<button type="button" onclick="fetchData()">Retrieve Zip Code</button>

<p id="Locations">No Zip Code Found</p>

<script>
function fetchData() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      document.getElementById("Locations").innerHTML = xhr.responseText;
    }
  };
  var zipcode = encodeURIComponent(document.getElementsByName("zipcode")[0].value);
  xhr.open("GET", "https://api.getlocation.io/v2/us/"+zipcode+"&"+zipcode, true);
  xhr.send();
}
</script>

This code retrieves the value of an input element with the name attribute set to "zipcode", encodes it for a URL, and then appends it to the API endpoint through string concatenation.

Answer №3

It seems like you are not utilizing JQUERY, instead opting for pure JavaScript. Here's an update for your code.

Please note that you have one field, but two values. This needs to be aligned first.

<input type="text" id="postcode" name="postcode" placeholder="Postcode"><br>
<button type="button" onclick="loadDoc()">Get Postcode</button>

<p id="Addresses">No Postcode</p>

<script>
function loadDoc() {

 Value = document.getElementById("postcode").value

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("Addresses").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "https://api.getaddress.io/v2/uk/"+Value+"&"+Value, true);
  xhttp.send();
}
</script>

Answer №4

To retrieve the value of the postcode field, use the code snippet below:

xhttp.open("GET", "https://api.getaddress.io/v2/uk/" + document.getElementById("postcode").value +"&" + document.getElementById("postcode").value, true);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Where should the logic for translating API responses to reducers be stored?

Upon receiving a request from the backend, I am presented with the following data structure: { total: 2, items: [...] } My objective is to store this information in the designated reducer like so: { value: [...] // items total: 2, fetc ...

Heroku experiencing instability with Javascript/MySQL project during requests

Currently facing a problem with my Heroku API developed in JavaScript that interacts with a MySQL database. Previously operational, now encountering an error on each API request: 2020-06-17T18:37:13.493711+00:00 app[web.1]: > <a href="/cdn-cgi/l/ema ...

Regular Expression - Invalid character detected in output

I'm currently in the process of developing a function to verify if a field is deemed acceptable based on a specific character set. In case it doesn't meet the criteria, I aim to determine and communicate which characters are not permitted. While ...

How can you tell if a browser window is minimized when a user is switching to another window on an iPhone?

Is it possible to detect when a browser window is minimized or becomes inactive while the user switches to a different window on an iPhone? I attempted to use jQuery's onfocus and onblur events ($(window).blur(...);) but did not receive any callbacks. ...

Creating a function within an ajax call presents a challenge that needs to be

Below is an example of my ajax function: for (var i = 0; i < 50; i++) (function(i) { jQuery('#skin_'+i).click( function() { var result = $('#idskin_'+i).val(); $.ajax({ url: 'aja ...

Comparing AngularJS controller and template encapsulation to Angular components: a breakdown

I've set up a state in my angularjs app called homeInside, complete with its own controller and template. Within that layout, I have various elements including a button with an ng-click event tied to the function doSomething. Additionally, there is an ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Use an EditText to capture user input, then pass the variables to a Webview by executing a javascript command

I'm currently working on a basic web application that aims to streamline the user experience by eliminating the need for repeated credential input upon website access (without saving passwords). After some exploration, I was able to identify and manip ...

Tips for maximizing the benefits of debounce/throttle and having a truly dynamic experience

Attempting to implement a similar concept in Vue: props(){ debouncing: {type: Number, default: 0} }, methods: { clicked: _.debounce(function() { this.$emit('click'); }, this.debouncing), } Unfortunately, the code breaks when ...

Finding a specific document in MongoDB using a unique slug within Next.js: A step-by-step guide

I have a collection of data in MongoDB structured like this: [ { "Post": "this is a post", "_id": ObjectId("630f3c32c1a580642a9ff4a0"), "slug": "this-is-a-title", "title" ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Empty response returned by Next.js API Routes

I have attempted various methods to retrieve data from a database using MySQL. Here's what I've tried: export default function handler(req, res) { const mysql = require('mysql') const dbConn = mysql.createConnection({ ho ...

Create a random word from a single string within the data in Nuxt.js

I am in need of assistance. In my Vue Nuxtjs project, I am fetching random words generated from my backend Laravel application through an API response. I need to generate multiple random words from a single string value in the data obtained from my Axios r ...

How can I handle optional props with defaults in React + TypeScript without relying on typecasting while ensuring strictNullChecks is enabled?

Consider the scenario where we have the following component: interface Props { someOptionalProp?: string; } class SomeComponent extends React.Component<Props, {}> { public static defaultProps = { someOptionalProp: 'some defaul ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

Encountering an error while configuring webpack with ReactJS: Unexpected token found while

I'm attempting to update the state of all elements within an array in ReactJS, as illustrated below. As a newbie to this application development, it's challenging for me to identify the mistake in my code. closeState(){ this.state.itemList.f ...

Error encountered when running NPM start - file path unable to locate JSON package file

Hello everyone, I'm new here and appreciate any help in advance! I'm currently working on my first project and encountering some challenges. The biggest one is that whenever I try to run npm start, I keep getting an error message: I've att ...

Uncover concealed words within PDF documents

While incorporating PDF.js to display LaTeX typeset PDF files on my website, I encountered an issue. I have concealed specific text in the PDF, but it remains searchable when viewed in Acrobat Reader. Is there a method to search for hidden text using PDF ...

Is there a way to attach a model to an Angular directive?

Currently, I am implementing angular's typeahead functionality using the following resource: I have created a directive with the following template: <div> <input type="text" ng-model="user.selected" placeholder="Ty ...

Utilize Vue.js to incorporate an external JavaScript file into your project

Currently, I am utilizing Vue.js 2.0 and facing an issue with referencing an external JavaScript file in my project. The index.html file contains the following script: <script type='text/javascript' src='https://d1bxh8uas1mnw7.cloudfro ...