/    Sign up×
Bounties /Pin to ProfileBookmark

JSONP and AJAX API search

+ 6,000
Copy linkTweet thisAlerts:
Apr 03.2023
<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Uppgift 3</title>

 <!-- Bootstrap -->
 <link rel="stylesheet" href="styles/bootstrap.min.css">
 <link rel="stylesheet" href="styles/style.css" />
</head>

<body>
 <nav class="navbar navbar-inverse navbar-fixed-top">
 <div class="container">
 <div class="navbar-header">
 <a class="navbar-brand" href="#">Uppgift 3</a>
 </div>
 </div>
 </nav>

 <div class="container">

 <div class="search-template">
 <h1>Sökning av livsmedel</h1>

 <form class="form">
 <div class="form-group">
 <label for="search-word">Livsmedel</label>
 <input type="search" class="form-control" id="search-word" placeholder="t ex makaroner">
 </div>
 <button type="submit" class="btn btn-default" id="sok-button">Sök</button>
 </form>
 <table id="search-table" class="table">
 <thead>
 <tr>
 <th>Livsmedel</th>
 <th>Energi (kcal/100g)</th>
 <th>Kolhydrater</th>
 <th>Protein</th>
 <th>Fett</th>
 </tr>
 </thead>
 <tbody>

 </tbody>
 </table>
 </div>


 </div>
 <!-- /.container -->

 <script src="scripts/jquery-3.3.1.min.js"></script>
 <script src="scripts/bootstrap.min.js"></script>
 <script src="scripts/getLivsmedelsData.js"></script>
</body>

</html>
function getLivsmedelsData(data) {
 const tableBody = document.getElementById("search-table").getElementsByTagName("tbody")[0];
 tableBody.innerHTML = ""; // Clear the table body
 
 if (data.livsmedel.length> 0) {
 data.livsmedel.forEach(item => {
 const row = tableBody.insertRow();
 
 const nameCell = row.insertCell();
 const energyCell = row.insertCell();
 const carbsCell = row.insertCell();
 const proteinCell = row.insertCell();
 const fatCell = row.insertCell();
 
 nameCell.textContent = item.namn;
 energyCell.textContent = item.energi;
 carbsCell.textContent = item.kolhydrater;
 proteinCell.textContent = item.protein;
 fatCell.textContent = item.fett;
 });
 } else {
 document.getElementById("search-table").style.display = "none";
 }
 }
 
 document.getElementById("sok-button").addEventListener("click", (e) => {
 e.preventDefault();
 const searchTerm = document.getElementById("search-word").value.trim();
 if (searchTerm) {
 const script = document.createElement("script");
 script.src = <span><code>https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php?namn=${encodeURIComponent(searchTerm)}&callback=getLivsmedel</code></span>;
 document.head.appendChild(script);
 document.head.removeChild(script);
 } else {
 alert("Please enter a search term.");
 }
 });

When the user clicks on the “Search button”, a search must be made against a food web service using so-called JSONP.

The search result should be presented as rows in the table found in index.html . Use the tbody element inside the table to hold your rows.

The result must consist of food names, energy and the distribution of carbohydrates, protein and fat, be ware of the orders.

  • When a new search is made, the result from the previous search must be deleted.
  • If the search results in zero hits, the table should not be displayed. In other words, the table header should not appear alone on the page.
  • If the search results in one or more hits, the table must be visible and show the result. The following image shows what a result might look like: 

food data must take place from a web service available at this URL:

https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php

If we are looking for “bacon” the website is

https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php?namn=bacon&callback=getLivsmedel

getLivsmedel({ 
 "livsmedel":[ 
 { 
 "namn":"Bacon gris",
 "energi":"345",
 "protein":"13.4",
 "fett":"32.8",
 "kolhydrater":"0"
 },
 { 
 "namn":"Bacon magert gris rökt stekt",
 "energi":"126",
 "protein":"21.5",
 "fett":"3.1",
 "kolhydrater":"1.1"
 },
 { 
 "namn":"Bacon lättbacon gris",
 "energi":"114",
 "protein":"19.4",
 "fett":"3.5",
 "kolhydrater":"1"
 },
 { 
 "namn":"Flygande Jakob Kyckling bacon jordnötter banan",
 "energi":"218",
 "protein":"14.8",
 "fett":"15.3",
 "kolhydrater":"5.3"
 }
 ],
 "responseStatus":200
})

Can anyone help me? I pressed the button, nothing happens. I got a empty list with a table head.

Need help with codes. This is completely new for me.

Please help me.

to post a answer
HTMLJavaScriptjQuery

7 Replies

Davinci•003 auto-replyThe provided HTML and JavaScript code creates a simple web page where users can search for food items using a web service. When a user enters a search term and clicks the "Search" button, the page sends a request to the web service using JSONP (JSON with Padding). The web service returns the food items matching the search term, and the results are then displayed in a table on the page.

Here's a brief explanation of how the code works:

1. The HTML code defines the structure of the page, including a search form, a table for displaying results, and references to the necessary CSS and JavaScript files.

2. The JavaScript code defines a function called getLivsmedelsData(data), which is responsible for displaying the search results in the table. It first clears any previous search results and then checks if there are any results to display. If there are results, it creates new rows in the table and populates them with the food item's name, energy, carbohydrates, protein, and fat. If there are no results, the table is hidden.

3. The JavaScript code also sets up an event listener for the "Search" button. When the button is clicked, it prevents the default form submission and retrieves the search term from the input field. If the search term is not empty, it creates a new script element with a URL containing the search term and appends it to the document's head. This effectively sends a JSONP request to the web service.

4. The web service returns the food data wrapped in a callback function, which is then executed by the browser. In this case, the callback function is getLivsmedel. However, your JavaScript code defines the function getLivsmedelsData, so you should change the callback parameter in the URL to callback=getLivsmedelsData to match the function name:

script.src = <span><code>https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php?namn=${encodeURIComponent(searchTerm)}&amp;amp;callback=getLivsmedelsData</code></span>;

5. When the callback function is executed, it receives the food data as an argument and uses the getLivsmedelsData(data) function to display the results in the table.

With these changes, your code should work as expected: When a user searches for a food item, the web service returns matching food items, and the results are displayed in the table. If there are no results, the table is hidden. When a new search is made, the previous search results are deleted.

Was this helpful?

Copy linkTweet thisAlerts:
@themolitorApr 04.2023 — I updated the Davinci•003 auto-reply 👍
Copy linkTweet thisAlerts:
@lizauthorApr 04.2023 — No, the code doesn’t work. The search doesn’t not search
Copy linkTweet thisAlerts:
@lizauthorApr 04.2023 — There are fail in browser console. I do not understand the failure
Copy linkTweet thisAlerts:
@lizauthorApr 04.2023 — Can you copy in the code and test?
Copy linkTweet thisAlerts:
@lizauthorApr 04.2023 — Hi,
I got this faioluire in webbrowser console
Uncaught SyntaxError: Unexpected token '<' (at getLivsmedelsData.js:31:18)
Copy linkTweet thisAlerts:
@prApr 11.2023 — To fetch JSON data from the URL, use the global (built-in) fetch() function.

I've added that here (and did a little refactoring)
function getLivsmedelsData(data) {
if (data.livsmedel.length {
const row = tableBody.insertRow();

const nameCell = row.insertCell();
const energyCell = row.insertCell();
const carbsCell = row.insertCell();
const proteinCell = row.insertCell();
const fatCell = row.insertCell();

nameCell.textContent = item.namn;
energyCell.textContent = item.energi;
carbsCell.textContent = item.kolhydrater;
proteinCell.textContent = item.protein;
fatCell.textContent = item.fett;
});
}

document.getElementById("sok-button").addEventListener("click", async (e) => {
const searchTerm = document.getElementById("search-word").value.trim();
if (!searchTerm) return alert("Please enter a search term.");

const url = `https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php?namn=${encodeURIComponent(searchTerm)}`;
const data = await fetch(url);
const json = await data.json();

getLivsmedelsData(json);
});
×

Success!

Help @liz spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...