Here is a simple example of how to invoke our RESTful web service to add a course from JavaScript:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Add Course - JSON</title> <script type="text/javascript"> function testAddCourseJSON() { //Hardcoded course information to keep example simple. //This could be passed as arguments to this function //We could also use HTML form to get this information from
users var courseName = "Course-4"; var credits = 4; //Create XMLHttpRequest var req = new XMLHttpRequest(); //Set callback function, because we will have XMLHttpRequest //make asynchronous call to our web service req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { //HTTP call was successful. Display response document.getElementById("responseSpan").innerHTML =
req.responseText; } }; //Open request to our REST service. Call is going to be asyc req.open("POST",
"http://localhost:8080/CourseManagementREST/services/course/add",
true); //Set request content type as JSON req.setRequestHeader("Content-type", "application/JSON"); //Create Course object and then stringify it to create JSON
string var course = { "course_name": courseName, "credits" : credits }; //Send request. req.send(JSON.stringify(course)); } </script> </head> <body> <button type="submit" onclick="return testAddCourseJSON();">Add
Course using JSON</button> <p/> <span id="responseSpan"></span> </body> </html>
If you want to test this code, create an HTML file, say addCourseJSON.html, in the src/main/webapp folder of the CourseManagementREST project. Then, browse to http://localhost:8080/CourseManagementREST/addCourseJSON.html. Click the Add Course using JSON button. The response is displayed in the same page.