How to interact with Web server using JavaScript - 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.

Related

Get ajax call progress status in front end

I have a web page which allows users to upload and process specific files. After an user uploads some files, after clicking the 'Process' button an ajax call is being sent to a backend service. In the beforeSend function there is an overlay applied to the screen and a spinner is displayed. When the success function is triggered, then the overlay is removed and a toast notification is being shown like 'Files were processed!'
My goal is to somehow show a progress status for each file based on specific checkpoints in the backend service.
Let's say that the backend service when called does following tasks: parse file, map to specific format, send data to database A.... and in the end it sends back http status 200 and a JSON like
{
"status":"Success",
"message": "File X was processed"
}
Now what I want is that instead of just getting an overlay and disabling the whole page until the success event is triggered, to have a progress bar which is updated for each file based on the exact step where the backend has reached.
For instance, for file A, I would like to see below transitions: 5 % Parsing file, 10 % Mapping file...90% sending data to database, 100% processed.
Is this somehow achievable?
There are few points that you need to look into.
Usually in production code, we need to have timeouts. If you are making an ajax call to the backend API, there will be a timeout associated with that api call. Suppose if the timeout is more than 2 mins, then it will send you a 504 Gateway timeout error.
To overcome this and to implement the functionality which you want, you can have any DB(lets consider SQL server). In your SQL server, make a table:
Process_Table
With schema:
Process_id( Will store the process id/name )
Percentage( Will store the percentage )
At_step ( Parsing, Mapping, Sending to DB etc)
Using Javascript(Or any framework of your choice), use setInterval(), to make check_process() api calls. For check_proceess, you can pass in the process_id, and check against the db. For interval, you can set it to 5 seconds. So that every 5 seconds the call is made.
You can read the response of those API calls and do your processing.
An HTTP request consists of a request and a response. There's no direct way to get status updates beyond the onprogress event which would let you see how much data has been transferred. This is useful for determining how much of the data has been sent to the server, but not so much for how far the server has got with working with that data.
You could store progress in a database and poll a webservice to read the most recent status.
You could also have the server push updates to the client using Websockets for bi-directional communication.
A rough outline for such a system might look like:
Open a Websocket
Send files with Ajax
Get server generated ID back in HTTP response
Pay attention to messages coming over the Websocket that mention that ID
You could also look at doing the whole thing over Websockets (i.e. upload the files that way too). A quick Google search turns up this library for uploading files to a Websocket service hosted on Node.js.

how to store javascript variable into php

I want store clickede_id value into $id2[] give me some suggestions and also suggest some advance details
function yes(clicked_id)
{
var it1=clicked_id;
alert(it1);
var tt1=1;
var tt2= "<?php echo($id2[var it1]); ?>";
//var tt2=document.getElementById("idcheck").value;
alert(tt2);
var tt3=document.getElementById("idcheck1").value;
//alert(tt3);
}
When you develop a web application, you are creating tools to let client and server communicates (over the HTTP protocol). This communication is based on Requests and Responses.
The client send request to server and the server responds with a reponse. In your case, you choosed PHP as the server-side language that will create your responses as answers to client request. Thes responses are HTML (+ javascript). Anyways, the reponses are static stuff to be interpredted by the client.
So the code you have sent is seen by the browser as:
function yes(clicked_id)
{
var it1=clicked_id;
alert(it1);
var tt1=1;
var tt2= 3; // or whatever value returned by php
var tt2=document.getElementById("idcheck").value;
var tt3=document.getElementById("idcheck1").value;
// ajax call here
}
When you say : store data from javascript to php (even if it doesnt look as a correct senetence), you mean sending data from client to server. It can be done via a classical Post request (via form submit with page refresh) or via ajax without page refresh.
For ajax, please to check jQuery documentation for $.ajax function (if you want to have a cross browser compatible solution), or XMLHTTPRequest object if you want raw javascript and do the cross-browser compatibility yourself.
PHP executes in the server and send the result to your browser to display. Your JS executes at this browser stage. What you need to understand is that PHP has already been finished it's execution when your JS gets a chance to execute. Trying to change something in PHP through the JS is trying to access the past.
But, the good news is, that you can adopt a model where you feed your JS through the PHP script (look at this echo "<script>var s = 'from php'</script>") and JS feeds your NEXT php execution. You can use ajax or direct page calling for this.
Probably you should read this question: How to pass data from Javascript to PHP and vice versa?

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.

Server Side Broadcast Update PHP

I want to build an application which will automatically broadcast notification(s) to a user when data on server is changed. So far, I just know one method of doing this i.e. using JQuery setInterval. Using this function, every client requests data through ajax to server, asking if something changed.
The weakness of this method is every client must send a packet every specific time interval, so my server receives huge data packet. It's so frustrating to manage the server. Are there any alternatives for this besides Jquery setInterval?
If Websockets is not an option for you, you could use one ajax request to the server. Than server side go into a infinite loop. Use the sleep function to not overload the memory. Than check each time if there is something changed. If so, break out the loop and return the data. On the client side send immediately the next request.
After a bit of research it's called "Ajax long-polling requests".
Here is a explanation.
The PHP code would look something like this:
$prevHash = $_GET['hash'];
while(true){
$currHash = GetHashFromTable('myTable');
if ($prevHash != $currRowCount) break;
sleep(3);
}
$response[0] = GetDataFromTable('myTable');
$response[1] = GetHashFromTable('myTable');
echo json_encode($response);
Update
Long polling is not the best option. Better to use web-sockets.
If you want to compare the differences, see this answer: https://stackoverflow.com/a/10029326/3269816

How should I handle many AJAX calls?

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.

Categories