1

I have code that uses AJAX and JSON to output a chunk of SQL data when you do a search and I am trying to separate the data some and have it display into an HTML table. At first it was just the SQL data but I put some tags into the innerHTML line to at least visually separate it, however I would really like to be able to put each column into a separate table cell. Any ideas on how to do that would be greatly appreciated. Here is the code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="js/jquery-2.2.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <title>AJAX Search Example</title>
    <script>
    function fetch() {
      // (A) GET SEARCH TERM
 
      var data = new FormData();
      data.append('search', document.getElementById("search").value);
      data.append('ajax', 1);

      // (B) AJAX SEARCH REQUEST
      var xhr = new XMLHttpRequest();
    
      // (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD
      
    xhr.onreadystatechange =  function (event) {
        // (CHANGE2) we will check if ajax process has completed or not it goes from 1,2,3,4 means end. 

if(this.readyState == 4){

// (CHANGE2) when ready state comes to 4 we then check what response status was it if it is 200 good else error. 

if(this.status == 200){
    // (CHANGE3) MOVED ALL YOUR CODE HERE 

// (CHANGE4) we need to use responseText instead of response because JSON comes as string that is why we are parsing it to be converted into array

var results = JSON.parse(this.responseText);
    //I have added just a measure to check what the out put is you can remove it latter. open dev console to get the result.
    console.log(results);

wrapper = document.getElementById("results");
    if (results.length > 0) {
          wrapper.innerHTML = "";

// (CHANGE5) UPDATED data ref with results 

for (i = 0; i <  results.length; i++) {
            let line = document.createElement("div");
              //it is just as simple to create id only it must start with alphabet not number 

line.id=`res${[i]}`;

//we created span tag to display price and this is what we will change. on that span we will create a data-price attribute which will hold original price and we will run calculations using that number 

//BIG CHANGE
//BIG CHANGE

//since after parsing individual record will be in Js object so we dont need to access them like array  results[i]['item']

//we access them with dot notation results[i].item

line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber} - Price:$<span data-price='${results[i].price}'>${results[i].price}</span>
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a>`; 
            wrapper.appendChild(line);
          }

 // (CHANGE6) We moved event listeners here so any newly added elements will be updated. 

 //get all the links and apply event listener through loop   
 
    var links = document.querySelectorAll('a');
      

      for ( ii = 0; ii <  links.length; ii++) {
         links[ii].addEventListener("click", function(event) {
         
       //capture link value and get number to be converted to percentage  
       
       var percentage = event.target.innerText.match(/\d+/)[0]/100;
 
 //capture the data-price which is within same div as anchor link
 
 var pricetarget = event.target.parentElement.querySelector('[data-price]');
 
 //get value of data-price
 
 var actualprice=  pricetarget.dataset.price;
 
 //run math and chnage the value on display
 
 pricetarget.innerHTML=(actualprice*percentage).toFixed(2);
      
      
      });
      }

        } else { wrapper.innerHTML = "No results found"; }

 } else {
 
 //if reponse code is other ethan 200 

alert('INTERNET  DEAD OR AJAX FAILED ');

 }

 }
       

            

      };

// (CHANGE7) We moved open event to end so everything is ready before it fires.

xhr.open('POST', "2-search.php");
      xhr.send(data);
      return false;

 
    };
    </script>
  </head>
  <body>
    <!-- (A) SEARCH FORM -->
    <form ID='myForm' onsubmit="return fetch();">
      <h1>SEARCH FOR CATALYTIC CONVERTER</h1>
      <input type="text" id="search" required/>
      <input type="submit" value="Search"/>
    </form>

    <!-- (B) SEARCH RESULTS -->
    <div id="results"></div>


  </body>
  </html>

Here is where I added the tags to at least visually separate it: "line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber} - Price:$${results[i].price}"

What I want to do is have Category, OEM #, and price each in a separate table cell. Thank you for any help offered.

1 Answer 1

1

You can simply generate trs inside your for (i = 0; i < results.len.. like you are already doing for divs . So , just use += to append every new tr inside tbody and then append this to your table

Demo Code :

//suppose json look like below :)
var results = [{
  "category": "A",
  "price": 13,
  "oemnumber": "d1A"
}, {
  "category": "B",
  "price": 15,
  "oemnumber": "d1B"
}, {
  "category": "C",
  "price": 12,
  "oemnumber": "d1C"
}]
fetch();

function fetch() {
  /*  var data = new FormData();
   data.append('search', document.getElementById("search").value);
   data.append('ajax', 1);
   var xhr = new XMLHttpRequest();

   // (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD

     //some codes/..    
    console.log(results);*/

  wrapper = document.getElementById("results");
  wrapper.innerHTML = "";
  var rows = "";
  if (results.length > 0) {
    for (i = 0; i < results.length; i++) {
      //generate trs
      rows += `<tr id=res${[i]}><td>${results[i].category}</td><td>${results[i].oemnumber}</td><td>$<span data-price='${results[i].price}'>${results[i].price}</span>
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a></td></tr>`;
    }
    wrapper.innerHTML = `<table class="table">
    <thead><th>Category</th><th>OEM</th><th>Price</th></thead><tbody>${rows}</tbody></table>`;

    //sme other codes,,

  }
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div id="results">
</div>

Sign up to request clarification or add additional context in comments.

9 Comments

I did the innerhtml part before but without the div part, maybe that is why it didn't work. I do not need the "+=" between each data result though?Like "wrapper.innerHTML += `<tr id=res${[i]}> += <td>${results[i].category}</td> += <td>${results[i].oemnumber}</td> += <td>$<span data-price='${results[i].price}'>${results[i].price}</span>"
One question,you have " wrapper = document.getElementById("somethings");" I have results there instead of somethings to go with the <div id="results">, now in your html you have <div id="results"> and <tbody id="somethings">. If I change the tag from results to somethings then results will be missing for the div tag. So how do I get the tag for the div and the tag for the table?
No , somethings is inside results div you can keep result div hidden at first after datas are loaded from ajax you can show result div and then append json inside your tbody .
OK, what I was asking was in your demo code you changed my "wrapper = document.getElementById("results");" to "wrapper = document.getElementById("somethings");". How would I go about having both the results and somethings tab in the code?
So you need to add table generated inside results div ? If yes you can simply generate whole table in your js code.. and then append that to your result div .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.