0

First of all, I've just started learning JavaScript so maybe some of the things you will see won't have sense at all so I would appreciate if you could be as detailed as possible.

I want to have an input text that when submitting, the value would be received by a script. When submitting I mean pressing the 'Enter' key. I'm working with the Accuweather API and I'm trying to get the key of a city (the one you write in the input field) using AJAX. This is what I've got:

HTML:

<form action="" onsubmit="getKey()">
      <input type="text" class="input-style" id="search" name="City"
      value="" autofocus="autofocus">
    </form>

JavaScript:

    var request = new XMLHttpRequest();

    function getKey() {
        var citySearch = *JSON link*;    
        var inputField = document.getElementById("search").value
        citySearch += inputField
        request.open('GET', citySearch);
        var keyJSON = JSON.parse(request.responseText)
        var key = keyJSON[0].Key
        console.log(key)
    }

//The console.log() at the end of the function is just for testing.

I've been doing some research and apparently I have to use PHP (which I know anything about) but I wanted to ask here if there's maybe an easier way. Thank you.

Arnau
  • 1
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Dave Sep 27 '17 at 21:25
  • 1
    @EdwardGizbreht what are you talking about?! ES6 classes and promises are in no way needed to solve this. – Scott Marcus Sep 27 '17 at 21:31
  • No, you don't need php, but you need to wait for the response before you start trying to process it. Have a google for **s**jax or see Dave's link – symcbean Sep 27 '17 at 22:49
  • There's so much wrong with this that I'm not sure where to begin. You need to read an introductory guide to binding event handlers (including preventing the default behaviour) and another introductory guide to the XMLHttpRequest object. – Quentin Sep 27 '17 at 22:52

0 Answers0