Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Last active September 10, 2017 19:36
Show Gist options
  • Save ti-ka/5d8d8e942e842b310ee1 to your computer and use it in GitHub Desktop.
Save ti-ka/5d8d8e942e842b310ee1 to your computer and use it in GitHub Desktop.
AJAX Rest API Call Sample - (response.json is the assumed file that API responds with)
<form onsubmit='APICall(); return false'>
<input type='search' placeholder='Enter Search Keyword' id="input" />
<input type='submit' value='Search'>
</form>
<!--Results will be here-->
<div id="show"></div>
<!--Include JQuery in the Site-->
<script src='https://code.jquery.com/jquery-2.1.4.min.js'></script>
<!-- JavaScript Function that calls API -->
<script>
function APICall(){
var input = $("#input").val();
//Making an ajax call to the API Site, say URL be: http://example.com/api/search.php?keyword=nepal
var url = "http://example.com/api/search.php";
var data = {
keyword : input
}
var request = $.ajax({
url : url,
data : data,
method : 'get',
dataType : 'json'
});
//When API Call is successful
request.success(function(response){
if(response.length === 0){
$('#show').html("No results found.");
} else {
var print = "";
//The response will be the json array of javascript. Let's make a table.
for (var i = 0; i < response.length; i++){
print += "<tr><td>" + response[i].name + "</td><td>" + response[i].city + "</td></tr>";
}
$('#show').html("<table>" + print + "</table>");
}
});
//If API CAll Fails
request.fail(function(response){
$('#show').html("Failed to get data.");
});
}
</script>
[
{
"name" : "Tika Pahadi", "city" : "Sindhuli", "country" : "Nepal"
},
{
"name" : "Rohan Shahi", "city" : "Kathmandu", "country" : "Nepal"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment