(I just started learning JavaScript and AJAX) in my project I need to get data from AJAX API using URL link. button "Get All" plug-in directly and works without problems, but if I need to find something specific (use the search form) variable from not transmitted in URL.
and i don't get any error messages
Attachments area
variable from <input type="text"/>
not transmitted in URL
----------
<button class="nav-link" id="getAllBtn">Get All</button>
<form">
<input type="text" placeholder="Search" aria-label="Search" id="currencyid" />
<button class="btn my-2 my-sm-0" id="searchBtn">Search</button>
</form>
$("#getAllBtn").on("click", function() {
console.log("home btn clicked")
$.ajax({
url: `http://www.example.com/`,
method: "GET",
success: function(result) {
clearAll();
$("#cryptoCards").html(getCurrenciesCard(result))
},
error: function() {
clearAll();
$("#cryptoCards").html("<h5>No Data!</h5>")
}
})
});
$("#searchBtn").on("click", function() {
const currencyid = $("#currencyid").val();
console.log("input: ", currencyid);
$.ajax({
url: `http://www.example.com/${currencyid}`,
method: "GET",
success: function(result) {
clearAll();
$("#cryptoCards").html(oneCurrencyCard(result))
},
error: function() {
clearAll();
$("#cryptoCards").html("<h5>No Data!</h5>")
}
})
});
A <button>
's type defaults to submit
- therefore you are submitting the form so none of your click
action will run
simplest solution is to make the button NOT submit the form
<form>
<input type="text" placeholder="Search" aria-label="Search" id="currencyid" />
<button type="button" class="btn my-2 my-sm-0" id="searchBtn">Search</button>
</form>
or another solution is to prevent the default behaviour
$("#searchBtn").on("click", function(e) {
e.preventDefault();
const currencyid = $("#currencyid").val();
you havent set data on ajax api. so ajax cant recognize your data. also, your request url is: http://www.example.com/ ${currencyid}, so your request would be: http://www.example.com/5 , and your server search this as url, function/method something else. Here is some ways to use get method:
one of these ways should work.
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.