Sherpa Sherpa - 22 days ago 10
Javascript Question

Fixed - AJAX and datalists

I'm trying to use XML to get a list of cities from a website, then go through and add each of the cities to a datalist so that when I put in an input it will filter the cities in the list.

example of city list:

Aleppo
Alexandria
Alger
Almaty
Ankara
Anshan
Baghdad
Baku
Bandung
Bangalore
Bangkok
Barcelona


*[Each city name is on a new line]

current html:

<div id="namearea">
<h2>City Name:</h2>

<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>

<button id="search">
Search
</button>

<span class="loading" id="loadingnames">
Loading...
</span>
</div>
</div>


current JS code:

window.onload = function() {
var request = new XMLHttpRequest();
request.onload = processCities;
request.open("GET", "url", true);
request.send();
};


Inspecting the page with Firebug shows that nothing is being added to the datalist, so I'm wondering what I'm doing wrong. I also tried using
.responseText
rather than
.responeXML
but it didn't make any difference. Can anyone help me?

[EDIT]
Progress has been made.
I changed the processCities() function to:

function processCities() {
var response = this.responseText;
var city = response.split("\n");
var options = "";

for(var i = 0; i < response.length; i++) {
options += "<option value='"+city[i]+"'>\n";
}
document.getElementById("cities").innerHTML = options;
}


This code seems to work.

Thanks for the help.

Answer

Here is an example of making the request. If you really are getting XML, you'll have to parse it. It's better if you could get json.

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Comments