Home » Jquery » jQuery AJAX for BigCommerce REST JSON Product API & Query String filtering

jQuery AJAX for BigCommerce REST JSON Product API & Query String filtering

Posted by: admin February 22, 2020 Leave a comment

Questions:

My first forray into AJAX with JQuery here. I’m a jQuery novice too but need real world scenario’s to learn on. I am writing a BigCommerce theme and as multi layer navigation on product attributes is not supported, I need to call their API and then render returned content.

I have built a PHP based REST service to obfuscate the API OAuth from the web front end and this is returning data well and quickly.

With the below, I intended to call the API for all of the products within a specific category and then generate a HTML based unordered list for each element of the JSON string. From here, I was going to use some more jQuery to strip the filter parameters from the query string and filter the list.

This is because you can’t ask the BigCommerce API for products filtered by attribute so I figured the quickest way and best UX was to grab the category data and then filter in DOM. Is that a crazy idea?
At present, I am just rendering the product name as a proof of concept and all is loading quickly even when running Stencil CLI on localhost.

The below is working but it currently replaces all <li> elements on the page rather than just create LI’s within a specific DIV. IF there is a way I can do this so only a specific DIV element is populated with the content, it would serve it’s purpose for now and I can re-use the code throughout the site as needed where different filters according to the owners brand guidelines are required.

Any advice on how to achieve this is greatly appreciated.

  <script>
 //jQuery to query middleware & return results via ajax.
  $('#usedBikeSearch').submit(function(event) {
    event.preventDefault();
      var post_url = $(this).attr("action"); //get form action urls
      var form_data = $(this).serialize(); //Encode form elements for submission
        $.ajax({
            url : post_url
            //data : form_data //To use once data loaded for filtering.
        }).done(function(response){
        var buffer="";
        $.each(JSON.parse(response), function(index, val) {
          for(var i=0; i < val.length; i++){
            var item = val[i];
            console.log(item.name);
            buffer+="<li><h3>"+item.name+"</h3></li>";
          }
          $('ul').html(buffer);
            });
          });
        });
</script>
How to&Answer: