When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude for more specific regions.

  1. After entering an initial zip code with the provided code below, everything works correctly, and I receive an alert with the JSON result as intended. However, if I change the zip code and submit it again, the program stops functioning properly. The updated zip is visible in the URL, but it disappears from the text input field, and the city function doesn't execute. It requires a second submission to work again. What could be causing this issue, and how can I fix it?

  2. Is using www.zippopotam.us/ a suitable approach for this project, or are there better alternatives available?

.

<div id="location">
<form onsubmit="city()">
<input type="text" name="loc" id="loc" />
</form> 
</div>

function city(){
var zip = $('#loc').val();
var client = new XMLHttpRequest();
client.open("GET", "http://api.zippopotam.us/us/"+zip, true);
client.onreadystatechange = function() {
if(client.readyState == 4) {
    alert(client.responseText);
};
};

client.send();
}

Answer №1

You have encountered a cross-domain security policy issue, meaning that data cannot be loaded from one domain to another without proper permissions.

To resolve this, consider making a request to your own server, which can then fetch the desired information from an external domain like zippopotam.us. This way, it appears as if the data is coming from your server, allowing the call to pass through successfully.

Alternatively, you can explore client-side solutions such as checking if supports JSONP (JSON with Padding). Other methods, like examining your provider's allow-origin header, may also help in addressing this issue.

For more in-depth information on cross-origin resource sharing (CORS), refer to: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

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

Exploring the depths of JSON nested maps in Groovy: a step-by-step guide

I have received the following JSON output from AWS DynamoDB and I am looking to loop through it in order to populate a table within Jenkins Parameters using a Groovy script. Is this achievable? JSON: [ { "test": { "S ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

Using VUE-JS to implement checkbox functionality with v-model

Click here for the image Greetings All, I am new to VUE.JS and seeking assistance. I have checkboxes for MODULES and FUNCTIONS My goal is to add functions for each module that I have. Below is a snippet of my code: <label> Modules:</label> ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Error: Unable to access property 'count.' because it is undefined

componentDidMount(props) { this.interval = setInterval(() => { if (props.count !== 0) { this.stateHandler() } }, 1000) } Encountering an issue with the interval, as the console is displaying the following error: Type ...

Utilizing Ajax for dynamic PHP result determination

HTML CODE <div class="card text-center pricing-card mb-20"> <ul class="list-group list-group-flush"> <?php $gbewas = mysqli_query($con,"SELECT * FROM price"); while($okks = mysqli_fetch_array($gbewas)) { ?> <li cla ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

Iterate through the array to verify that the specified conditions are satisfied for each individual item

I am working with an array of items and need to check if they all meet specific criteria. I've created a for loop to iterate through the array, but I'm concerned about its efficiency. Is there a more optimal way to achieve this? let match = 0; ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

Understanding XML parsing problems

I've decided to keep the live xml/atom-feed URL private, as it's hosted on LiveJournal. However, I'm a bit confused about how this all works: let XML_URL = "https://users.livejournal.com/<username>/data/atom"; $(function(){ ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

Exploring a JSON Object with nested properties, crafting changes, and producing a fresh object: A step-by-step guide

I am attempting to manipulate a JSON object with nested properties by replacing numeric values with computed values and returning a new object. The original object looks like this: var obj = { "a0": { "count": 41, "name": "Park", "new": { ...

How to change a date object into a datestring using the TZ format in JavaScript

Here is the input: const date = "06/01/2018" const time = "06:25:00" The desired output format is a string like this: "2018-06-01T00:55:00.000Z". I attempted to create the Date object using const result = new Date(date + time); //outputs an obje ...

What is the best way to store a JSON string in the NSUserDefaults?

I am trying to implement caching for a variable that I can retrieve and display in different parts of my app. Specifically, I have a JSON request that returns parameters like name, and I want to cache the value of the name parameter. For example, if the n ...

What is the best way to convert an array to JSON in Swift?

I am having trouble extracting the value "maxtemp_c" from a JSON request. This is my attempt so far, but I keep encountering issues when trying to parse the JSON data and end up with a nil value: //I have the URL of the json let url = URL(string: "http:/ ...

"Creating visual art with processing in 2D using P5

Recently, I came across a webpage about rendering 2D objects in processing using JavaScript. Here is the link to the page: Upon trying out the example code provided on the page in a new P5 project, I noticed that the code structure looked like this: HTML ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...