Making a chat function on my website - javascript

I want tto make a chat on my site.
Very basic I want people to login to chat. And when they do that I show them the last 5 messeges.
When the person is writting something it is put into the database, and then reloads the site, with the new text from the database. So it only works when the user writes something, because it will only update when he press 'Write'.
To make it even better I am thinking of making a javascript to look up the content of the database and every 3-5 seconds.
Is that the right way to do it or is there a better way??

a lot of chat services on websites use java or flash rather than javascript, the reason is that those languages provide socket support which means they can have a permanent open connection to the server for updates.
with javascript you have to poll the server at a regular intervals using ajax or comet which is a technique for long polling, but it does have to re-establish connections every now and then.
when html5 is more widespread you will be able to use web-sockets to listen to the server for updates, but for now ajax or a flash based plugin (even to just provide sockets for js to use) is the most viable option.
something like this will provide a socket-swf-js type bridge to talk to your server
http://code.google.com/p/jssockets/

Yes, recently i've made a simple groupchat application with javascript and php and i used to check the text file where all the chat messages i'm writing to for every 2 secs....
<div id="chatbox"></div>//html div element where i've to paste the message data
$("#submitmsg").click(function(){
$.post("post.php", {text: send_mymsg});//where am sending my data to a php file to write into a html file "log.html"
}
function loadLog(){
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
});
}
setInterval (loadLog,2000);

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.

ASP.NET call a Javascript function

I'm working on a project that uses IP Payments to process transactions. The project involves a web form written in ASP with Code-Behind written in C#.
IPP offers an iFrame implementation, where you can put an iFrame in your page and display a small IPP page with fields for entering credit card information. The idea behind this is that the credit card info will only be handled by IPP and never by the server running the page, thus there is no requirement to ensure that card data is kept secure.
In order to display the IPP page in the iFrame though, a session needs to be initiated with IPP. The server initiates the session, and passes in a SessionID variable. Upon a successful session initiation, a Secure Session Token is returned to the server. The server then needs to "force" the client's browser to GET or POST the SessionID and the SST (Secure Session Token) to the IPP website. This is where my problem is.
I wrote a Javascript function in the ASPX page that would accept two parameters - the SessionID and SST - and send them to the IPP website. I'm now trying to call this Javascript function from my C# code upon successful initiation of the IPP session. However, I have been completely unable to do so.
I've done a lot of searching, and the one answer I keep coming across is to use either RegisterStartupScript or RegisterClientScriptBlock. The problem is, these seem to insert text directly into the page, rather than calling an existing function. Assuming I inserted my function into the page via one of those functions rather than writing it into the page myself, it still doesn't solve my problem of how to call said function.
Now it is possible that I'm going about this the wrong way, and there's a much better way to get the client's browser to GET/POST the SessionID and SST; if so, please tell me. I'm inexperienced with web programming and am thus learning as I go and making up solutions along the way that are quite likely not ideal.
Thanks in advance.
I think this should work:
Lets say you have something like this in your HTML:
<html>
<head>
<script>
function sendValuesToIPP(sessionId, sst){
//do stuff
}
</script>
</head>
</html>
If you do this in your C# code it should work
ClientScriptManager.RegisterStartupScript(
this.Type,
"some_key_you_want_to_identify_it",
string.Format("sendValuesToIPP('{0}','{1}')", SessionID, SST),
true);
Keep in mind that I'm assuming you have SessionID and SST properties server side, you can get them from wherever you want and just add them to the string that will actually call the function when registered in your ASPX.

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.

How far can I go with JavaScript?

I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.

Categories