Hi, I do not know how to explain my question well, but I will do my best.
It turns out that I have created an API in node.js and I want to interact with it through jquery. It's a simple case where I have to do a search. If I directly implement the search in the input, for example:
$("input").on("change input textInput", ()=>{.....})
works perfect, but what I want is to click on a button and it works the same and what happens is that it does not show any info or the console.log()
.
Next I put the code that does not work. I reiterate that the problem is in the jquery because api responds well.
<html>
<head>
<meta charset="UTF-8">
<title>Search Animals</title>
<script src="jquery.js"></script>
</head>
<body>
<h3>Find Animals</h3>
SPECIES: <input name="species"><br>
<input id="button" type="submit" value="Enviar">
<div id="container"></div>
<script>
$("#button").on("click", () =>{
//Captur
var species = $("input[name='species']").val();
var query = '?';
if(species) query += 'species=' + species;
//Creando la URL
var url = 'http://localhost:3000/findAnimals/' + query;
console.log(url);
//Creando la peticion JSON
$.getJSON(url, (animals, status)=>{
console.log(animals);
var container = $("#container")
animals.forEach((animal)=>{
container.append('<p>' + animal.name + '</p>');
});
});
});
</script>
</body>
//-----En el servidor Node.js
app.use('/findAnimals', (req, res) =>{
var query = {};
if(req.query.species)
query.species = req.query.species;
if(Object.keys(query).length != 0){
Animal.find(query, (err, animals)=>{
if(!err){
res.json(animals);
}else{
console.log(err);
res.json({});
}
});
}else res.json({});
});