Consuming a web service using JS and HTML - javascript

I am looking to create a client browser interface which will utilise the dictionary web service at Glosbe API. The user should be able to enter a word or a phrase into an input component and submit it without the page reloading. The returned data needs to be displayed on the page in a usable format so that they are able to find and read the meanings.
I've attempted this by creating a web service through Netbeans but I'm unsure whether this is the right method. Is it as simple as creating a HTML page and using javascript to call the api for Glosbe?
Any help would be highly appreciated.

You can use an XMLHTTPRequest from javascript to poll a web service. The XHR object is great for allowing you to make a request to a page or submit a form without having to refresh the page. When the request is made, it can be done asynchronously to allow the page to continue with other events and then handle the response and update the HTML. There are tons of resources on google that can instruct you on implementing an XHR object and the proper error handling along with sample code.
As far as the returned data being displayed in a usable format, that would need to be done by your JS when the response comes back. You can parse the response for the data you want and build the appropriate HTML element through JS to update your UI.
HTML
<input type='text' id='word'>
<input type='buton' onclick='sendMessage()'>
JS
function sendMessage()
{
var XHRrequest=new XMLHttpRequest();
XHRrequest.onabort = function() {
};
XHRrequest.onloadend = function (evt) {
};
XHRrequest.onreadystatechange = function() {
if (XHRrequest.readyState == 4 && XHRrequest.status == 200) {
//parse XHRrequest.responseText for response and build object
//this is where you update your UI with an HTML element
}
else if (XHRrequest.readyState == 4 && XHRrequest.status!=0) {
console.log("Error: returned status code " + XHRrequest.status + " " + XHRrequest.statusText + "\r\n" + XHRrequest.responseText);
//error handling for failed response
}
};
XHRrequest.ontimeout = function() {
alert("Error: event timed out");
};
XHRrequest.open("POST", WEBSERVICE_URL_HERE, true);
XHRrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHRrequest.send("word="+document.getElementById('word').value); \\request data goes here
}

Related

Upload data to the db without stopping the loading of the site

I have a small problem, I created a data analysis system on my site. Everything works, only that every time I run the post to be able to insert the data in the db, it slows down the loading of the site a lot. I was wondering if it was possible to load the data in the database without stopping the execution of the site. For example, if I load and click on an item in the menu I would like it not to let me wait for the data to be entered in the db but to continue with the click I made on the menu item.
My code works this way.
I take the data that interest me with javascript and I post to a php page for data entry
Thank
I don't know if you are using AJAX calls to pass the value from frontend to PHP.
If not, try to use AJAX calls calling the PHP page for data entry and passing the values you want to store. AJAX calls are asynchronous so JavaScript does not have to wait for the server response.
This is an example of AJAX call:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "data_entry.php?value1=exampleOfValueBeingStored1&value2=exampleOfValueBeingStored2", true);
xhttp.send();
}
in the REST paradigm if you need to update values you should use PUT or POST instead of GET. GET should be used only when you want retrieve values already inserted inside database for example.

Two Different Javascript Alerts before redirecting in ASP.NET

I want to show different alert messages using JavaScript. Here is my code, but my alert box will not show before the redirect. I tried the other examples provided but those are all using just one type of alert message. I use this ShowAlertMessage method to show other types of warnings as well, in which I don't want to redirect to any other page. Just give the user a warning.
If (user creates a new work order)
{
ShowAlertMessage("Property work order " + txtWorkOrderNumber.Text + " created successfully");
}
else
ShowAlertMessage("Property work order updated successfully");
Response.Redirect("~/DashBoard.aspx");
public static void ShowAlertMessage(string msg)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
string script = "alert(\"'" + msg + "'\");";
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", script, true);
}
}
You're sending a Response.Redirect, which means your response does not have any content, but rather just the URL to redirect to.
In order to do what you're trying to do, you'd have to write out the javascript to the current page, then once the alerts fire, use javascript to move to a new URL.
Maybe something like the following:
string script = string.Format("alert('{0}'); window.location.href='{1}';",
msg, ResolveUrl("~/Dashboard.aspx"));
This is a common example of a problem with WebForms - it's very difficult to properly mix client and server code together to provide a good user experience, which is why I much prefer doing my user experience stuff completely in javascript, with AJAX to do most of the posts.

Using JQuery to get JSON from Flask is returning null sometimes

So I am developing on oracle Linux Server release 6.6 and I recently switched over to Apache 2.4 for my web server. I am developing a Flask web service so I was using Flask's local WSGI server to do all my debugging.
In the application, i have a form and when you click the submit button, it does a JQuery $.getJSON() call to my Flask backend. Then in the backend, I return JSON data and alert the user of the data. The problem is that most of the the time it returns null and doesn't return my data. Other times it returns my data and everything is fine. This worked perfectly when I was using the local WSGI server. It was once I migrated to Apache when this error started happening so I believe the problem is from Apache.
Also I print out my json data before returning so I know for sure it is not returning null data but I still get this error.
My HTML/JavaScript code
<div id="restore_submit" class="restore_submit" style="display:none;">
<form onsubmit="restoreDB()">
Type the database ID and Snapshot ID of the database you want to restore
<br><br>
RDS ID:<br>
<input type="text" id="DbName2" name="DbName">
<br>
Snapshot ID:<br>
<input type="text" id="snapshot_id" name="snapshot_id">
<br><br>
<input type="submit" value="Restore">
</form>
</div>
function restoreDB() {
var DbName = document.getElementById('DbName2').value;
var snapshot_ID = document.getElementById('snapshot_id').value;
var check = confirm('Are you sure you want to restore ' + DbName);
if(check){
$.getJSON('/restore_rds', {
Dbname: DbName,
snapshot_id: snapshot_ID
}, function(data) {
if(data){
if(data && data.error){
alert(DbName + " is being restored using this snapshot_id " + snapshot_ID);
}
else{
alert(data.error);
}
}
else{
alert("returned null");
alert(data);
}
});
}
}
My Python code
#This is for the restore script
#app.route('/restore_rds')
##login_required
def restore_rds():
DbName = request.args.get('Dbname')
snapshot_id = request.args.get('snapshot_id')
error = rds_action.restore_db(DbName, snapshot_id, rds)
if error:
error = str(error)
else:
error = 'empty'
print error
print jsonify(error = error)
return jsonify(error = error)
EDIT:
So i fixed the issue after like a week of digging. Looks like my requests were getting cancelled before returning back to the webpage. So what i did was a e.preventDefault() in my JavaScript function.
so in my html i change it to
<form onsubmit="restoreDB(event)">
and in my JavaScript i added this
function restoreDB(e) {
e.preventDefault();
Now the webpage doesn't reload and it has enough time to wait for a response. Probably not the best fix but I am just happy I fixed it. If anyone recommends anything better, that will be great
So i fixed the issue after like a week of digging. Looks like my requests were getting cancelled before returning back to the webpage. So what i did was a e.preventDefault() in my JavaScript function.
so in my html i change it to
<form onsubmit="restoreDB(event)">
and in my JavaScript i added this
function restoreDB(e) {
e.preventDefault();
Now the webpage doesn't reload and it has enough time to wait for a response. Probably not the best fix but I am just happy I fixed it. If anyone recommends anything better, that will be great

Real time insertion of data in mvc

I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?
The code I am using to get the comment :
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
And This code for storing comment in database :
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.
First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.
USING WindowTimers.setInterval()
Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:
function checkNewData() {
// ajax call
// On response, if found some new comment, you will inject it in the DOM
}
Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:
// Method written in PHP
public function ajax_checkNewData() {
$time = time();
// Asks to your model controller if has something new for us.
// SELECT comment FROM comments WHERE timestamp > $time
// Then return its response
}
You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.
USING WEBSOCKETS (beautiful way)
Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.
Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.
For further information check it out:
REFERENCES
Get Started: Chat application - http://socket.io/get-started/chat/
Websockets - http://en.wikipedia.org/wiki/WebSocket
WebSockets - https://developer.mozilla.org/en/docs/WebSockets
Good luck!
You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database.
Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.
It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.
You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC
https://github.com/WaleedChayeb/SignalRChatApp

How to Show the progressbar like incremental status updates for long requests

I have to send the longtime request to server in my Asp.net application, that request i called 4 services, each service take max of 1min , so i want to show prograssbar which service is completed , i searched one link Example, it is correct about my concept but that link using iframe to load another page that page write method like
protected void UpdateProgress(int PercentComplete, string Message)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}');</script>",
PercentComplete, Message));
// To be sure the response isn't buffered on the server.
Response.Flush();
}
In this code to call javascript function in parent aspx page to update details , but i have in same page to handle that concept , i removed "Parent." in my code get the error object expected how to write the code in single page
With help of jQuery (http://jQuery.com) you could do the following in javascript:
function callServices() {
var serviceUrls = ["http://yourdomain/svc1", "http://yourdomain/svc2", "http://yourdomain/svc3", "http://yourdomain/svc4"];
for(i = 0; i < serviceUrls.length; i++) {
$.ajax(serviceUrls[i], function(){ updateStatus("Service " + i); });
}
}
function updateStatus(svc) {
$("#statusBar").append("<span>" + svc + " has finished.</span>");
}
Cheers!

Categories

Resources