0

I am in a pickle with this problem.

I have a text area and I want to click on a button to

  1. transform the address text into uppercase
  2. loop through the data I've acquired from an API and check to see if the addresses match up.

I've been working on it for a couple of days searching through stackoverflow questions and the Mozilla docs for answers. I've tried just doing step one and I've been getting Uncaught SyntaxError: Unexpected end of input errors. But I believe my syntax is correct.

HTML

<form>
       <p>Check to is if street light service has already been requested</p><br>
       <input type="text" name="service" id="chiService">
       <button type="button" id="btn">Try it</button>
     </form>

Javascript

$.ajax({
url: "https://data.cityofchicago.org/resource/h5ea-dn36.json",
type: "GET",
data: {
  "$limit" : 4,
  "$$app_token" : "APP_TOKEN"
}
 }).done(function(data) {


var el = document.getElementById("btn");


function serviceFunction(myData){
 var userStreetAddress = document.getElementById('chiService').value;
 userStreetAddress = userStreetAddress.toUpperCase();
 /*for(var i = 1; i < myData.length; i++){
    if(myData.street_address[i] == userStreetAddress){
         console.log('its working!');
     }
 */} 
   alert(userStreetAddress);
  };
el.addEventListener("click", serviceFunction(data), false);


});//end of ajax function
Community
  • 1
  • 1
Zaynaib Giwa
  • 5,366
  • 7
  • 21
  • 26

2 Answers2

0

You may try a full jquery implementation a little nicer looking:

$.ajax({
url: "https://data.cityofchicago.org/resource/h5ea-dn36.json",
type: "GET",
data: {
  "$limit" : 4,
  "$$app_token" : "APP_TOKEN"
}
 }).done(function(data) {

$('#btn').click(function(){//the click event
 var userStreetAddress = $('#chiService').val().toUpperCase();//get the value
 $.each(data,function(i,v) {//the loop
  if(v.street_address == userStreetAddress) {
         console.log('its working!');
     }
 });
})
});//end of ajax function
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

The reason "serviceFunction(data)" is called immediately is because you specified to click listener (el.addEventListener) to call it immediately to click. If you want to invoke ajax call on click and then run "serviceFunction(data)" on receiving ajax response, you may try:

var el = document.getElementById("btn");
el.addEventListener("click", serviceFunction(data), false);
function serviceFunction(myData){
$.ajax({
url: "https://data.cityofchicago.org/resource/h5ea-dn36.json",
type: "GET",
data: {
  "$limit" : 4,
  "$$app_token" : "APP_TOKEN"
}
 }).done(function(myData) {   

 var userStreetAddress = document.getElementById('chiService').value;
 userStreetAddress = userStreetAddress.toUpperCase();
 /*for(var i = 1; i < myData.length; i++){
    if(myData.street_address[i] == userStreetAddress){
         console.log('its working!');
     }
 } */
   alert(streetAddress);

});//end of ajax function
}
Prabhu Vinod
  • 328
  • 2
  • 10