Home > Back-end >  Get data that's in the JSON but not in the table/HTML
Get data that's in the JSON but not in the table/HTML

Time:02-24

I'm trying to get the information that is in the url but JavaScript returns to the HTML table "undefined". Does anyone have any idea what mistake I might be making.

Get data that's in the JSON but not in the table/HTML

<!DOCTYPE html>
    <html lang="en">
    
    <link rel="stylesheet" href="Request.css">
    
    <h2>Quary</h2>
    
    <form id="form" method="GET">
        <label for="Year">Year:</label><br>
        <input type="text" id="year" name="year" autocomplete="off" required><br>
        <input type="submit" value="submit">
    </form>
    
    <table>
        <thead>
            <tr>
                <td>Year</td>
                <td>Data</td>
            </tr>
        </thead>
        <tbody id="movie-table-body">
    
        </tbody>
    </table>
    

FROM HERE Java-script

    <script>
    var form = document.getElementById("form")
    
    document.getElementById('form').addEventListener('submit', function (evt) {
    
        evt.preventDefault();
        var year = document.getElementById("year").value
    
    
        let params = {
            "year": year,
        }
    
    
    
        let query = Object.keys(params)
            .map(k => encodeURIComponent(k)   '='   encodeURIComponent(params[k]))
            .join('&');
    
        let url = 'https://mudfoot.doc.stu.mmu.ac.uk/node/api/halloffame?'   query;
    
        fetch(url)
        
            .then(data => data.text())
            .then((text) => {
                console.log('successful', text)
                let = tableHTML = ""
    
                for (let i = 0; i < text.length; i  ) {
                    tableHTML  = "<tr>";
                    tableHTML  = "<td>"   text[i]["year"]   "</td>";
                    tableHTML  = "<td>"   text[i]["data"]   "</td>";
    
                    tableHTML  = "</tr>";
                };
    
                document.getElementById("movie-table-body").innerHTML = tableHTML;
            })
            .catch((error) => {
                alert(error);
            })
    
        })
    </script>

</body>
</html>

CodePudding user response:

Can I see the response from the url. You can find this from network tab in the console browser, can you use response.json() instead

CodePudding user response:

You receive a text, you must convert to JSON data.json(). Response from request is a object, so you can't iterate the object, you must iterate a array

let tableToHtml = ""
text[data].map(d => {tableToHtml  = json.stringify(d)} )

If you want to add all keys in object, use for...in


for (b in data) {
tableToHtml  = b;
} 
  • Related