简体   繁体   中英

JS not executed after AJAX call

I am working on a small weather app. On the front end, I have a search bar and whenever the user type something, I am loading a list of cities that match with the value of the user input and ordered by population with a limit of 10.

This functionality is now working: a ul of li cities in generated.

Now it seems my app.js is locked on the AJAX , I am trying to add an event listener for every li elements onclick but it does not execute at all. Seems that it has to due with async / sync.

index.php

<body>
    <?php require_once("config/db.php")?>
    <h2>Weather</h2>
    <input type="text" name="city-search" class="city-search" id="city-search">
    <ul class="result f32">
  ...
</ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="scripts/app.js"></script>
</body>

app.js

const search = document.querySelector("#city-search");
const results = document.querySelector(".result");
const listCities = document.querySelectorAll(".cities-select");


// works
search.addEventListener("keyup", e =>{
    let city = search.value;
    if(city != ""){
        loadCities(city);
    }
});


// works
const loadCities = (city) => {
    $.ajax({
        url: "config/fetch-cities.php",
        method: "GET",
        async: true,
        data: {
            query: city
        },
        success: function(data){
            results.innerHTML = data;
        }
    });
}

// does not execute 
listCities.forEach(city => {
    city.addEventListener("click", e =>{
        console.log("hello world");
    })
})

fetch.php

<?php 
require("db.php");

if(isset($_GET["query"])){
    $search = $_GET["query"];
    $results = $conn->prepare("SELECT * FROM cities WHERE city LIKE '{$search}%' 
    ORDER BY population DESC LIMIT 5");
} 

$results->execute();
foreach ($results as $row) {
    echo '<li class="cities-select">
     <div> '.$row["city"].' </div>
     <div> '.$row["country"].' </div>
     </li>';
}
?>

From what I can see, you are calling addEventListener before .cities-select exists (you load the page -> tries to loop over .cities-select but it doesn't exist). You need to add your event listeners in your $.Ajax#success function, after you have set .innerHTML .

const search = document.querySelector("#city-search");
const results = document.querySelector(".result");

// works
search.addEventListener("keyup", e =>{
    let city = search.value;
    if(city != ""){
        loadCities(city);
    }
});


// works
const loadCities = (city) => {
    $.ajax({
        url: "config/fetch-cities.php",
        method: "GET",
        async: true,
        data: {
            query: city
        },
        success: function(data){
            results.innerHTML = data;
            const cities = document.querySelectorAll(".cities-select");
            cities.forEach(city => {
                city.addEventListener("click", e =>{
                    console.log("hello world");
                })
            })
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM