calling rest services with jquery
Learning JQuery:
http://www.w3schools.com/Jquery/default.asp
Code for these examples is here: https://github.com/gnurmatova/JQuery-REST
Installing:
<script src=“http://code.jquery.com/jquery-latest.min.js"> or download and include the same file
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test" .
$("#test").hide() - hides the element with id=“test”.
All JQuery methods go in:
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
to call a REST service from JQuery:
Code for these examples is here: https://github.com/gnurmatova/JQuery-REST
Installing:
<script src=“http://code.jquery.com/jquery-latest.min.js"> or download and include the same file
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test" .
$("#test").hide() - hides the element with id=“test”.
All JQuery methods go in:
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
to call a REST service from JQuery:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> $(document).ready( function() { $.getJSON("http://localhost:8080/unh/rest/song", function(dat) { console.log(dat['data'][0]) }); }); </script> </head> <body> </body> </html>
the handler function function(dat) will have the resulting JSON in the dat variable that can then be referenced as a map/array.
Try:
console.log(dat)
console.log(dat['data'])
output the value of the title of the third element
You can also use the parsed JSON to write the data back to the screen:
Try:
console.log(dat)
console.log(dat['data'])
output the value of the title of the third element
You can also use the parsed JSON to write the data back to the screen:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> $(document).ready(function() { $.getJSON("http://localhost:8080/unh/rest/song", function(dat) { var songs = dat['data']; $.each(songs, function(count, obj) { document.write("<br/>"+(count+1)+". <a href = 'http://localhost:8080/unh/rest/song/mvc/getsong?id=" + obj['id'] + "'>" + obj['title'] + " by " + obj['artist'] + "</a>" ); }) }); }); </script> </head> <body> </body> </html>
using metadata service to provide description of a song
Following very simple implementation of metadata will provide the description of a song. At this time we assume that all fields are text and there is no validation needed on the data entry
@GET @Path("metadata") @Produces({ MediaType.APPLICATION_JSON }) public Response getSongMeta() { Song song = new Song(); try { @SuppressWarnings("unchecked") HashMapsongHM = mapper.convertValue(song, HashMap.class); songHM.remove("id"); return Response.status(200).entity(mapper.writeValueAsString(songHM)).build(); } catch (JsonProcessingException e) { e.printStackTrace(); } return Response.status(500).build(); }
and the service to use this metadata:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> //we are reusing this URL, somove it to a variable base_url="http://localhost:8080/unh/rest/song"; meta_url="http://localhost:8080/unh/rest/song/metadata/"; $(document).ready(function(){ $.getJSON(meta_url,function(data){ $.each(data, function(key, value){ $("div.song_form").append("<br/>Please enter " + key + ":"+"<input type='text' name='"+key+"'"+">"); }); }); }); </script> </head> <body> <h1 style="text-align:center;">Create a new Song</h1> <div class="song_form"></div> <input type="Submit"> </body> </html>
post with jquery
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> //we are reusing this URL, somove it to a variable base_url="http://localhost:8080/unh/rest/song"; meta_url="http://localhost:8080/unh/rest/song/metadata/"; $(document).ready(function(){ $.getJSON(meta_url,function(data){ $.each(data, function(key, value){ $("div.song_form").append("<br/>Please enter " + key + ":"+"<input type='text' name='"+key+"'"+">"); }); }); $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; $('#song_form').submit(function(){ console.log($('#song_form').serializeObject()); postData($('#song_form').serializeObject()); return false; }); function postData(data){ $.ajax({ type: "POST", url: "http://localhost:8080/unh/rest/song", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", crossDomain: true, dataType: "json", success: function (data, status, jqXHR) { alert("success"); }, error: function (jqXHR, status) { console.log(jqXHR); alert('failed, please check console for errors'); } }); } }); </script> </head> <body> <h1 style="text-align:center;">Create a new Song</h1> <form id="song_form"> <div class="song_form"></div> <input type="Submit"> </form> </body> </html>
delete with jquery
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> //we are reusing this URL, somove it to a variable base_url="http://localhost:8080/unh/rest/song/"; $(document).ready(function(){ $('#song_form').submit(function(){ deleteData($('.ids').val()); return false; }); function deleteData(ids){ $.ajax({ type: "DELETE", url: base_url+ids, success: function (data, status, jqXHR) { alert("deleted"); }, error: function (jqXHR, status) { console.log(status); alert('failed, please check console for errors'); } }); } }); </script> </head> <body> <h1 style="text-align:center;">Delete a Song</h1> <form id="song_form" method="POST"> Enter the Id of the song to be deleted: <input type="text" class="ids"> <input type="Submit"> </form> </body> </html>