In this post we will demonstrate how to call Restful web service using jQuery ajax call. jQuery simplifies the calling process for a Restful service. If you trying to implement it on your page than this post will help you.
We are explaining both GET and POST method for a web service using jQuery. In this action perform on the button click. So lets start how to process it.
Steps to consume Restful Web Service Using jQuery:
First create an HTML page and placed an button on it. Mention button ID attribute to add event listener. Like this:
1 2 3 4 5 6 7 8 |
<html> <div> <button id="btn-action">Follow Playlist</button> </div> </html> |
Now add below mentioned js library in your page <head> element.
1 2 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> |
Write down jQuery code to track button click event. You should use button ID for it.
Use addEventListener to get button click event. Than create an function to GET web service data. Place below script code in your page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<script> var follow_track = document.getElementById('btn-action'); follow_track.addEventListener('click', function() { follow_usr_func().then(function(response) { }); }); function follow_usr_func() { return $.ajax({ var accessToken : 'tokenvaluehere', url: 'https://api.example.com/v1/me/following', type: 'GET', headers: { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json', }, success: function(response) { alert(response); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } </script> |
If your want to consume POST rest web service call, just change the “type” value to POST in script code.
Check These Tutorials:
jQuery Interactive Parallax Effect for Background Layers
How to Use jQuery Email Autocomplete in HTML Form
How to Upload Multiple Images Using jQuery Ajax
POST Web Service Parameters using jQuery:
If you want to pass some parameter along with the POST AJAX call, than use “data:” attribute for it. See below script function example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function follow_usr_func() { return $.ajax({ accessToken : 'Token Value Here', url: 'https://api.example.com/v1/me/tracks', type: 'POST', headers: { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json', }, async: false, data: { "useridval": "546789890" }, success: function(data) { alert(data); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } |
Today we learned the way to call restful web service via jQuery. Hopefully this tutorial will help you to implement this functionality. Happy Coding.