0

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>
Belder
  • 720
  • 8
  • 17
  • This has been previously answered in another post: http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax – occasl Feb 12 '17 at 00:15

3 Answers3

2

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...

$('form[role="search"]').submit(function(ev)  {
  ev.preventDefault();
  // get the input value with:
  var searchstring = $('input[type="text"]', this).val();
  // your ajax request, using the variable above
  var 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=" + searchstring;
  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);
    }
  });
}); 
Constantin Groß
  • 9,010
  • 4
  • 17
  • 44
  • Me too...It took me a couple days to figure out how to properly get the results from the Api to display on my page. I thought adding the click handler would be a breeze, but again, I am very new to all of this so I'm happy enough to get part of it right. I tried the above suggestion but I'm not still getting any results to show. syntax looks right and I deleted the (url += "&keywords=";)... hmm... – Belder Feb 12 '17 at 00:13
  • If you delete the keywords parameter completely, no wonder you're not getting anything back! :) try `url += "&keywords=" + searchstring;` instead – Constantin Groß Feb 12 '17 at 00:24
  • Well, of course that makes sense! :) I'm thinking that the solution lies in the parameter I give to "&keywords=" although adding searchstring wasn't doing it for me. I have a feeling this is turning more into a question about how to use Ebay's Finding API that how to implement a click event handler. I just can't seem to find what I'm looking for in their documentation. – Belder Feb 12 '17 at 01:21
  • But if the results were as intended with the hardcoded string, they should also work for the same string as the value of the input now. Is that not the case? – Constantin Groß Feb 12 '17 at 01:30
  • Oh, stupid me, I forgot to add the `val()` after selecting the input. I updated the answer, please try again! – Constantin Groß Feb 12 '17 at 01:32
  • No, it doesn't seem to be the case. Hardcoded works fine though. – Belder Feb 12 '17 at 01:41
  • Even after my most recent change? Do you see any error messages in the developer console? – Constantin Groß Feb 12 '17 at 01:42
  • ReferenceError: searchstring is not defined at HTMLDocument. This is after adding your change, which I also thought would work. – Belder Feb 12 '17 at 01:46
  • Maybe a stupid question, but: You did put the ajax call inside the click handler callback function, in the spot where I wrote the comment, right after declaring the searchstring variable? – Constantin Groß Feb 12 '17 at 01:51
  • Here's a fiddle that shows that the variable is set correctly and the success callback is triggered. But the results are not showing even with your originally hardcoded string. https://jsfiddle.net/d4t862bo I'll have another look at it tomorrow when I got dev tools at hand. (but then again, the request cannot return anything usable without a valid app id - but at least it should show you whether there's still anything wrong on your end) – Constantin Groß Feb 12 '17 at 02:23
  • Very strange. When I insert my App ID for the API, the fiddle you created works fine and displays the alerts and results on the page. In my browser (Chrome) using the same code I'm still not getting any alerts or results to display. I AM getting a 200 OK response in my terminal though. When I go back to hardcoding the search term everything displays fine again. – Belder Feb 12 '17 at 12:40
  • That is absolutely strange... Can you make the not working page available somewhere? Don't know how to keep your app id private doing so, but I would need to see it in action in order to be able to analyse anything – Constantin Groß Feb 12 '17 at 13:11
  • Funny thing is that now everything is working in development but still not in production. I did do a bundle install before sending everything to Heroku however the only thing that was changed was adding the Rails12Factor gem which shouldn't have anything to do with it. I literally did nothing else so I can't think why the results have decided to appear (on my localhost at least) unless Ebay was having an issue with the API. – Belder Feb 12 '17 at 13:53
  • It's all working now. I just had to change the ebay url from http:// to https:// for it to work in production. Also, I added $(window).load(function() { to the beginning of my scripts which must be why I was getting a 200 OK response without the results showing before this was added. Thanks again & I really appreciate your help in solving this. – Belder Feb 12 '17 at 14:22
0

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.

  1. Put that ajax call into a function that you can call
  2. Give the button an id
  3. On document ready, use jquery to attach an event handler to the element with the id in step 2 above that triggers a call to your function mentioned in step 1 above.

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.

barnard
  • 61
  • 5
0

Given your current HTML, you can call a click event on your submit button like this...

$('button[type="submit"]).on('click', function(event) {
    /*
      since the button is of type "submit",
      prevent the default behavior. Which,
      in this case, is to submit the form.
    */
        event.preventDefault();
        //Check your browser's console to see what this is
        console.dir(event);
        //insert AJAX code here
});

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 as event, 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 a console.dir(event); call. More specifically, e.currentTarget/e.target, and view 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.

Community
  • 1
  • 1
SidTheBeard
  • 212
  • 2
  • 10