Conor T Conor T - 14 days ago 5
HTML Question

How do I take input from a bootstrap search bar and put it into a ajax call to retrieve data?

Im using HTML, Javascript and bootstrap to build a web application and have hit a wall, I tried using

document.getElementById("input here")
but that just returned a array of 0. I want to take data from an api and then display it on a media list, im trying to use the search bar as a way of filtering the api GET with a key word as ive read this is possible in the api im using.

$(document).ready(function(){
$("button").click(function(){
var word = document.getElementById("sbar");
$.ajax({
url: 'https://community-food2fork.p.mashape.com/search?key=0ee5a01caf7f7c3512b54978628f1a4e&q=' + word, // The URL to the API. You can get this in the API page of the API you intend to consume
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function(data) {
search = JSON.parse(JSON.stringify(data.recipes));
console.dir(search);
},
error: function(err) {
alert(err);
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "KEY HERE"); // Enter here your Mashape key
}
});
});


The HTML for the input:

<div class="container">
<div style="background: rgba(60, 255, 60, 0.2);" class="jumbotron">
<h1>Meal Manager</h1>
<p class="lead">A simple recipe app that provides ingerdiants fast.</p>
<div class="input-group">
<input type="text" id="sbar" class="form-control" aria-label="...">
<div class="input-group-btn">
<button type="button" class="btn btn-default" id="button" title="Search Database">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn" title="Sort by reviews" >
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn" title="Sort by trending" >
<span class="glyphicon glyphicon-hand-up" aria-hidden="true"></span>
</button>
</div>
</div>

Answer

Your code is almost fine. HTML is missing some div closing and also your JS. (At least the snippets you pasted here).

I've built this JSFiddle to test it and it works.

Just change:

url: 'https://…&q=' + word

to:

url: 'https://…&q=' + word.value

Your API call works and it's responding:

{"message":"Invalid Mashape Key"}

which is totally logic since your need to replace the "KEY HERE" part for a real key. Check Mashape Keys

xhr.setRequestHeader("X-Mashape-Authorization", "KEY HERE");