I have:
PHP Socket Server
PHP Pages to handle communication with server & db
Client .php page, which uses javascript/canvas to display & interact with a game.
What I want is for the user to connect and authenticate using the PHP pages which will initiate a socket connection to the server. Based on the information from that socket some chat info and events might be triggered to load data into client php page.
What is the right way to handle this. In all instances that I've ajax in before, the user triggers the event, not the server and javascript waits around for the php page's response.
What piece of php code from the php socket lets me send messages to the canvas elements?
Here's an example as the above is probably not very illuminating:
IE:
PHP reads off of its socket connection {"name":"msg","from":"user1","time":12345,"msg","hello world"}
At this point what does PHP do?** So that ...
The client has a div with "id='Incoming'"
I want to launch the following javascript:
function handleMessage(msgObj) {
var cText = document.getElementById("Incoming").innerHTML;
cText += "(" + msgObj.time + ")" + msgObj.from + " says: " + msgObj.msg +"<br/>";
document.getElementById("Incoming").innerHTML = cText;
}
I guess I'm trying to figure out how a client's web page is supposed to talk back to the php sockets...
Is this possible or do I need to make a client in flash, java, etc?
You send stuff from client to server when you've got data to send (e.g. user submits a button) typically via an event handler. The websocket also fires event when it receives data from the server (socket.onmessage). Simples.
ws.onmessage=function (evt) { handleMessage(evt.data); };
(or just change your handleMessage function body to use msgObj.data as the text value)
What piece of php code from the php socket lets me send messages to the canvas elements?
What websocket implementation are you using? They all have different APIs (NB a websocket is not the same thing as a network socket)
You should use Comet:
http://en.wikipedia.org/wiki/Comet_(programming)
AJAX is much better and also asynchronous
http://www.ape-project.org/
http://www.stream-hub.com/
...
http://cometdaily.com/maturity.html
or use HTML5 WebSockets
Related
I wanted to schedule sending of report(chart made by javascript) via email in a weekly basis. To have that, I need to convert first the chart(made by javascript) to image using php(AJAX) and upload to the server then send it.
I'm already using node.js in my server but ajax doesn't work there.
Is there's any way to get the same goal I want?
ReferenceError: XMLHttpRequest is not defined I got this error in the terminal.
Is there any error in my code?
var CronJob = require('cron').CronJob;
new CronJob('10 * * * * *', function() {
ajax_request=new XMLHttpRequest;
ajax_request.onreadystatechange=function(){
if(ajax_request.readyState==4&&ajax_request.status==200){
console.log('You will see this message every second');
}
};
ajax_request.open("GET","http://domain.com/test.php",true);
ajax_request.send();
}, null, true, 'Asia/Manila');
Why would ajax not work with node.js? AJAX simply sends data with javascript via the HTTP protocol, it does not have any restrictions in regards to which backend setups it works with, as long as they support the HTTP protocol.
You can generate the image with node.js, you dont have to use PHP
I have been working with jquery/ajax requests. I have successfully got a ajax request which will retrieve data from a database, the problem is, that i'm constantly serving window.setInterval() to refresh this function every x amount of seconds.
How would I change this to keep the ajax request alive, so it updates the html content without having to serve multiple requests to my ajax script.
My code follows:
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'Ajax.php'+SearchTerm, dataType: 'json', success: function(rows)
{
$('#NumberOfVotes').empty();
for (var i in rows)
{
var row = rows[i];
var QuestionID = row[0];
var Votes = row[1];
$('#NumberOfVotes')
.append(Votes);
}
}
});
});
}, 500);
A lot of this depends on how your server would be able to update it's content dynamically. That said, what you are looking for is websockets. Websockets are designed to replace the long-polling paradigm.
EDIT: Since you use mainly php for your server technology, look at Ratchet. I've heard good things about it http://socketo.me/
Here is an excellent article on using websockets with HTML
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
.NET has a great socket library in SignalR
http://signalr.net/
There is a myriad of php documentation on sockets out there
http://php.net/manual/en/book.sockets.php
look into using web sockets - you could send the client a message anytime they need to go an look for new data - that way your not making any unnecessary requests. Try checking out pubnub -service is cheap and could handle everything you need.
You could set xhr.multipart = true and modify server code. see Multipart Responses Example Code. Alternative way is to use websockets as mentioned
You need something server side that keeps the request alive until it has something to return. This is usually called "Comet", "Long-polling" or "Push".
The principle is :
You send a request client-side via AJAX
Your server receives the request, and doesn't return a response yet. It sleeps/waits until it has something to return
A new entry in your database ! Your server now has something to return : it returns some JSON data for the waiting request
Your receive the response server side, display what you have to display, and go back to step 1 sending another request.
Now, the implementation server side will depend on the language/framework you are using.
Edit :
Some examples using PHP :
Comet and PHP
Simple Comet Implementation Using PHP and jQuery
I've been working on a project for a couple of Minecraft servers that use Bukkit. I'm trying to create a web page that contains a dynamic map of the servers' worlds, as well as a real-time event update system, where a <div> is updated as events happen on the server. To give a brief outline of how my system works, the Minecraft servers communicate events with a Node.js webserver over the same network via UDP packets, and the Node.js webserver uses these packets to build JavaScript objects containing the event info. The objects are then stored, and passed to Jade whenever the page is requested. Jade takes care of the templating.
What I want to do is update this page dynamically, so that the user doesn't have to refresh the entire page to update the list of events. What I'm trying to implement is something like the Facebook ticker, which updates every time a Facebook friend does something like posting a status, commenting on a post, or 'liking' a post.
In reading this question on SO, I've concluded that I need to use long polling in a PHP script, but I'm not sure of how to integrate PHP with a webserver written almost entirely in Node.js. How could I go about doing this?
EDIT:
I've run into a problem in the clientside code.
This is the script block:
script(src='/scripts/jadeTemplate.js')
script(src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement("item");
jade.render(newsItem, 'objTemplate', { object: obj });
$('#newsfeed').prepend(newsItem);
console.log(obj);
alert(obj);
});
And this is objTemplate.jade:
p #{object}
// That's it.
When the alert() and console.log() are placed at the top of the script, it alerts and logs, but at the bottom, they don't execute (hence, I think it's a problem with either the creation of newsItem, the jade.render(), or the prepend.
If I need to provide any more snippets or files let me know. I'm still tinkering, so I might solve it on my own, but unless I update, I still need help. :)
I'd skip PHP and take a look at socket.io. It uses websockets when possible, but it will fall back to long-polling when necessary, and the client side library is very easy to use.
Whenever your node.js server has a new object ready to go, it will push it to all connected browsers. Use ClientJade to render the object using your template (you may have to break out the relevant part of the main template into its own file), then prepend the generated dom element to your feed.
First, if it isn't this way already, you'll need to break out the relevant part of your jade template into its own file. Call it objTemplate.jade. Then use ClientJade to create a compiled template that can be run in the browser: clientjade objTemplate.jade > jadeTemplate.js. Put jadeTemplate.js in your public js directory.
In your node.js app, you'll have something like this (pseudo-codey):
var io = require('socket.io').listen(httpServer);
listenForUDPPackets(function(obj) {
saveObjSomewhere(obj);
io.sockets.emit('obj', obj);
});
Then on the client, something like this:
<script src="/js/jadeTemplate.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement();
jade.render(newsItem, 'objTemplate', obj);
$('#newsFeed').prepend(newsItem);
});
</script>
Whats the best way to do a RPC (Remote Procedure Call) from a webpage or from JavaScript code? I want to keep it in JavaScript if possible so that I can do live updates to the webpage without having to do anything in PHP in case my server goes down I still want the JavaScript to handle page updates... possibly even sending a request to a python shell script running locally... Is this legal from JavaScript?
I prefer having remote machines handling the requests. I see a lot of talk about how XMLRPC or JSONRPC can do this however, I haven't seen any good examples. I guess Microsoft suggests using their XMLhttprequest however, I haven't seen anything that doesn't use their ActiveX call or require special code for Internet Explorer... I just want some simple way of passing a command to some python/ruby/c++ code from a webpage.
Python Server Code (Waiting for a RPC Request):
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def my_awesome_remote_function(str):
return str + "awesome"
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()
EXAMPLE JavaScript Code:
var client = rpc.server("http://localhost:8000/");
var my_local_variable = client.my_awesome_remote_function(param);
Is there a good JSON/JavaScript example someone can point me to that sends a request to a server and gets some data back from that server?
Thanks!
Hardly it will work this way: client.my_awesome_remote_function. There's no magic in js like __call in php. Also remote calls are done in js mostly asynchronously using idea of callback - function which is called after finishing of some task.
var client = rpc.server("http://localhost:8000/");
var my_local_variable;
client.rpc('my_awesome_remote_function', [param], function(result) {
my_local_variable = result;
});
You can easily find tutorials about that calls. Just google "ajax tutorials".
E.g.: http://www.w3schools.com/ajax/ajax_intro.asp (event though w3schools isn't the best site and have errors in some details, it is still good for beginners).
All ajax implementations use both modern both XMLHttpRequest and ActiveX control for older IE.
It is possible to run those requests synchronously, but is considered very bad from the point of user experience. Also, you'll need to deal with concept of callbacks anyway.
I am working on a project of web calendar. I want to add my php database file to the java script file. When I click on the save button of calendar, the entries showed in calendar, but I m unable to add PHP file to save button. So when I click on save button, the entry should go to the database(php file).
code goes here:-
buttons:
{
save : function()
{
calEvent.id = id;
id++;
calEvent.start = new Date(startField.val());
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.body = bodyField.val();
$calendar.weekCalendar("removeUnsavedEvents");
$calendar.weekCalendar("updateEvent", calEvent);
$dialogContent.dialog("close");
},
cancel : function() {
$dialogContent.dialog("close");
}
}
There is no such thing as a "PHP database", and you cannot add PHP to your JavaScript file.
Your save button needs to send data to a PHP via page via HTTP, either by regular post-back or AJAX. The page will reside and execute on your server, while the JavaScript calendar executes in the client's browser. That PHP page can then talk to a database server to store/retrieve data for you.
Your server must:
be set up to execute PHP files correctly
have a running database server (PostgreSQL, MySQL, etc)
have a database and table in which to hold your data
You must understand that a database is at the server end (sometime the web server).
It could by Sybase, MySql, SQLite, ...
Nothing to do with the server.
Javascript on the browser can and sometimes is turned off. It just makes it easier and more interactive to use the web pages.
So why should summat go to a php file? This makes no sense along with php base. Please have a little reflection on the various technologies involved.