How should I handle many AJAX calls? - javascript

I am trying to write a plugin which will work a lot with my server. Every page load will invoke an AJAX call to my server for data, the server should return a simple string.
Now I am trying to understand what would be the best aproach for this type of program.
Should I just create an AJAX call every time I need the data or is there some method I could create an open connection (despite the change of webpages) to save on server power?
Should I somehow listen to some port or something of the sort?
Do I have other options or what should I do to do this the most efficient way?

You can use HTML5 websockets (http://www.html5rocks.com/en/tutorials/websockets/basics/)
If you use this approach, then you will need to re-think the way you program your webserver, since websockets don't follow the request-response paradigm AJAX do. Instead they use a connection to stream data so you will need to open a port on your server and listen to it, the way to do it depends on the language or framework you are using. This is fast and responsive but will only work on most modern browsers.
Other approach is using Long Polling (http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery). This is used by some chat clients. It works sending an AJAX request to the server, the server receives it and keeps it waiting until the data is available and then the response is sent. Then the client makes another request, waits and repeats.
Probably you will almost never want to send simple strings to the client. It's almost always better to use XML or JSON to encode the response.

Just create a simple AJAX call and put it on each page, or save it as it's own file and put a server include on each page in the header. Simple as that!
$(document).load(function(){
$.ajax({
type: "POST",
url: "/where_your_string_is.php",
success: function(msg){
$("#stringHolder").html(msg);
}
});
});

Websockets API allows bi-directional communication, but I've just found that there's another option called HTML SSE that might be used if you only need to pull data. So if you've stumbled upon this question, consider this option as well.

Related

Questions about "response.redirect" on Kitura

Hi guys,
I'm not familiar with web server, client and AJAX. I encountered redirect problems on Kitura.
The delete route can redirect to "/api/v1/users/list" succeeded.(I saw a message through print function)
but the browser doesn't reload data(refresh) for /api/v1/users/list.
Please following code, Thanks!
Q1-0)Do I need to perform a manual refresh for browser?
Q1-1)If I should, which side is better for that? (server side or browser side)
Q2)Do I need to do refresh action by manual, when I using AJAX delete method?
Server side method "delete"
---------------------------
...
router.delete("/api/v1/users/delete/:id" ....
_ = try? response.redirect("/api/v1/users/list", status: .seeOther)
...
Server side method "get"
------------------------
...
//list all users.
//each user have a delete button that performs AJAX delete method to "/api/v1/users/delete/:id".
router.get("/api/v1/users/list", ...
print("get /api/v1/users/list")
...
Short answers:
Q1-0: In your case, yes.
Q1-1: In your case, browser.
Q2: In your case, yes.
Longer answer:
This really depends on the architecture of your app:
Client/server: You build an API that sends/receives JSON or XML through REST endpoints. On top of that, you build a JavaScript client that uses AJAX to communicate with this API. This is what you seem to be doing. However, your AJAX requests should only send/receive JSON or XML data. Any page updating, reloading or redirecting should happen client-side.
Server-side: Here, most of the logic happens on the server. You use HTTP GET and POST to request pages and submit forms. The server then processes these requests and returns an HTML page for the browser to render. See https://github.com/svanimpe/swift-blog for an example that uses Kitura and Stencil.
Client/server is more flexible as you can build several clients (web as well as native apps) for the same API, but is also more complex, as it's a distributed architecture and usually involves multiple programming languages and some code duplication.
Server-side apps are generally easier to build for beginners as they are monolithic and involve very little non-Swift code (in your case).

How to run a java program through a JavaScript page?

I have a java program to scan vehicle's number plate and i want to call this program through a JavaScript page i.e. When I click a button on my JavaScript page it should execute my java program . I know there are similar questions on stackoverflow, but none was clear enough for a beginner like me to understand. New to JavaScript, any help would be highly appreciated. Thank you in advance.
While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
You can do it with AJAX.
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
A simple example would be something like this
$.ajax({
type: 'POST',
url: 'http://localhost:8080/MyMethod',
data: JSON.stringify({"string" : "anything you want to send to your method"}),
contentType: "application/json",
error: function() {
alert("Failed");
},
success: function() {
alert("Success");
}
});
That depends on where you would like to run it on.
1.client side
The only method to get java codes running directly on client side, is to use a java applet. Write an applet,write your html properly, then you are all set.
Or, you may want a wasm/javascript compiler for java.
2.server side
you should setup a mechanism letting your frontend to raise the backend.
for frontend, you should be able to send certain requests. you can choose http request, aka XHR/AJAX, or, you can choose web socket. they are similar things.
For backend, if you let your httpd handle the very request, then you should have your httpd notify your code for that. The solution if different for different httpds.
If you want to handle the request directly, then you can just listen to the very port and do the regular things. You should be responsible for security issues.

How does one limit rate of api calls despite page reload?

Suppose I am using a free API service with a limit of c calls per m minutes.
I am using a tiny bit of javascript linked by the main html of my very basic site which contains something like the following:
$(function () {
//stuff
function getSomething() {
return $.ajax({
type: 'GET',
url: targetURL,
data: dataObject,
});
}
getSomething().done(function (returnedStuff){
//process returnedStuff
});
//more stuff
});
I have two questions:
Will there be an api call each time the page is reloaded?
If the answer to above is YES, then how does one prevent/limit the user/some other event from overshooting the api limit by their repeated reloading of the page.
Thanks for the help.
tldr: Making some assumptions from your high level example:
Will there be an api call each time the page is reloaded? Yes
If the answer to above is YES, then how does one prevent/limit the
user/some other event from overshooting the api limit by their
repeated reloading of the page. Read below
Further explanation:
Depending on whether your example code hits your own server side code which then makes the API code...or whether you're calling the API directly from the client. If you call the function on reload (document ready or whatever), then it will execute on every reload. Else, obviously only when you call the method (like via button click).
Remember, client side code is visible to the client - thus if that's your architecture, then you're exposing your API to the client. I can then for example write my own javascript to loop and call your API repeatedly...
My assumption is that the data does not need to refresh on every reload. With that in mind, I suggest you do the following:
Suggested way to limit API calls:
Use an ajax call to your own server.
On the server side, persist the data via caching of your choice and build in your own logic to test whether data needs to be refreshed (first call, after timeout, etc).
This way you do not expose the API url and details to the client side, and you have control over the amount of calls made to the API.
For optimization purposes, you can also rather cache data client side...but keep the logic and API call server side.
Hope this helps!
ps. If you need an example, please just provide what platform you're coding in and I'll be more than willing to whip up a quick example for you!
pps. You can simply cache client side and makde the API call from there with some logic built in to test the cache - but obviously anyone can then still call your API.

Can I use jquery and AJAX to call a cgi-bin script, then add message event to handle Server Sent Event?

What I have is a long running cgi-bin program (runs for 3-15 minutes) that I want to call using AJAX. While its running, I'd like to receive Server Sent Event data from it and display it on my web page. Kinda like a progress monitor - but more like a chat window that is updated automatically as the script runs.
Here's how I'm calling the script:
var Params = []; // a large array containing values... not shown.
$.ajax({
type: "POST",
url: 'cgi-bin/datagen.cgi',
data: { "id:: 1, "params": Params },
dataType: "json",
success: function( db ){ console.log( "done" ); }
});
I like the ease of using $.ajax(... to POST a lot of json data to a script, but I don't see a way to switch to Server Sent Event messaging to receive (listen) for return data.
Using SSE instead of ajax, I don't see (and can't find an example) of POSTing a lot of data to the script.
I can't (yet) use Websockets either - so SSE is really my only choice.
-AC
Unfortunately, SSE does not support POST data. This is an annoying oversight in the standard; especially given that the browsers typically just implement EventSource as a variation of XMLHttpRequest, which already does allow POST.
One (messy) option is to have your cgi write its progress to a log file, and then write a SSE server script that polls that log file. You'll have two sockets open to the server, one for the ajax call, one for the SSE. Yuk.
The better option is to use the long-poll (also called comet) approach. You need to use the XMLHttpRequest object directly, instead of jQuery's $.ajax(), but it is not so bad. The advantage is that (on most browsers) you get what you want to do for free, as your xhr object is having onreadystatechange() called with all that progress information your back-end script is sending. You can tell the difference between progress information and the final result by looking at xhr.readyState: 3 means it is in progress, 4 means it is done.
Check out chapter 7 of HTML5 Data Push Apps with SSE (O'Reilly) for more explanation (Disclaimer: my book), or you'll find plenty of information on the web. Chapter 9, on authentication, is where I moan about the lack of POST support in SSE, and show how to add workarounds to the application that was built-up in earlier chapters.

How to interact with Web server using JavaScript

I am trying to develop an Interactive chat application using AppWeb open source web Server.
I need to have some machanism that will enable Web server to send updated messages to client, so that when remote usre sends messages that will get updated automaticaly at the client end.
There are some methods to do this using HTML5 Web Sockets and Server sent events.
But we need to implement it in HTML and JavaScript only not HTML5.
So I need some pooling machanism that will keep pooling my Web Server for New events.
So how should I write pooling machanism in Javascript using Sockets.
How it should be implemented at server end?
Thanks!
there are already some examples out there... depending on the server-side, you could go for java-hello-world or php-hello-world or ...
if you can't use websocket, you have to can go the old way, create an interval by window.setInterval and pull data from the server with eg. $.ajax(). i don't know any other alternative to bidirectional connection (websocket)... see kayahrs answer
as you've asked for it:
$.ajax() is the jQuery way to do xhr. basically, it fires an asynchronous request to the server, which returns xml or json or text or ... (whatever). when this request comes back, the supported eventHandler gets fired and you can react to the response. you could also use the plain xhr, but it's a bit awkward to handle the original xhr.
jQuery supports some shorthand overloads for $.ajax(), eg. $.getJSON(), $.get(), ...
sample implementation:
$.get("test.cgi", function(data){
alert("Data Loaded: " + data);
});
There is another technique for sending messages from the server to the client. You have to use an iframe for this which connects to a PHP script (Or whatever technique you are using on the server side) which does not close the connection. The PHP script then sends JavaScript messages whenever the client must be informed about something. After each message the server flushes the output stream to enforce that the data really finds its way to the client and is not cached by some output buffer. Here is a small example code of the PHP script loaded in the iframe (not tested and not complete, just to show the basics):
<html>
<body>
<script type="text/javascript">
function receiveMsg(data)
{
// Do something with the data, for example send it to some function
// in the parent frame (Where your chat application lives)
}
<?php
while (true) // You may also implement some abort state which should
// be checked here
{
$data = waitForData(); // This is your magic function on the server
// which waits for data to be send to the client
echo "receiveMsg('" . $data . "');"; // Let's say data is just a string.
// You may want to use JSON instead
flush();
}
?>
</script>
</body>
</html>
Advantage of this method is that it doesn't rely on polling. So you don't have to send requests to the server every x seconds. And when you do things right on the server side then messages sent by one user are received as fast as possible by the other users and not x seconds later. Disadvantage is that you have a permanent HTTP connection for each chat user. But this may need less resources on the server then having dozens of complete HTTP requests per minute per chat user.

Categories