I’ve set up an Ajax request to the Ebay API using Jquery, which works while I have a search term/keyword hardcoded, but I cannot figure out how to write the code to make my (bootstrap) button trigger the Ajax request using the search form input. I’ve tried various things to no avail. I’m completely new to this and this is my first time making an Ajax request and using JQuery so hopefully this makes sense.
Jquery:
$(document).ready(function() {
url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=rare soul 45"; //This would get deleted?
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
3
Answers
I’m a bit surprised you managed to get an ajax request running but you struggle with registering a click event handler. 🙂 but here we go…
It looks like you are making that ajax call upon document ready which is not really what you want. You want to make that call upon a button press event. So I would do this.
Then, don’t forget to extract the value in the field from the event and place it into the called ajax function as a parameter.
Given your current HTML, you can call a click event on your submit button like this…
This code uses the jQuery .on() method to capture the given event,
'click'
, on a given element$('button[type="submit"]')
. Once this event has been captured, you can access it asevent
, or name of your choice, within the function.This
event
object contains information regarding the event itself. It can be quite daunting at first, but I encourage you to look through aconsole.dir(event);
call. More specifically,e.currentTarget
/e.target
, andview
to get a sense of what is going on. From there you can look into what the difference is between some things that seem the same and get as familiar with it as you’d like.