How to make the text/id I give can be brought from the URL I am requesting

Viewed 30

I need to write an ID (from 1 to 10) and to be displayed on a table but I don't know how to bring the ID I wrote to the print, how do I display ONLY the data from certain ID of the json file?

<label for="ide">ID:</label>
<input id="ide" type="search" placeholder="ID" name="ide">
<button id="boton" type="submit">Buscar</button>
<table class="table bordered">
    <thead>
        <tr>
            <th>UserID</th>
            <th>ID</th>
            <th>Title</th>
            <th>Completed</th>
        </tr>
    </thead>
    <tbody id="tabla">
    </tbody>
</table>
function ajax() {
    const url = "https://jsonplaceholder.typicode.com/users";

    axios.get(url)
        .then((res) => {
            show(res.data)
        })
        .catch((err) => {
            console.log(data);
        })
}

function show(data) {
    for (const id of data) {
        tabla.innerHTML += `
            <tr>
                <td>${id.id}</td>
                <td>${id.name}</td>
                <td>${id.username}</td>
                <td>${id.email}</td>
            </tr>
        `
    }
}

document.getElementById("boton").addEventListener("click", function() {
    ajax();
});
1 Answers

Declare a variable for id first

let id = 0

document.getElementById("ide").addEventListener("onchange", function(e) {
    id = e.target.value
});

Your ajax function should be like this:

 function ajax() {
        const url = `https://jsonplaceholder.typicode.com/users/:${id}`;
    
        axios.get(url)
            .then((res) => {
                show(res.data)
            })
            .catch((err) => {
                console.log(data);
            })
    }
Related