Node.js with cron job and ajax - php

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

Related

Dynamically get data from database using Ajax without a refresh interval

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

HTML5 game <-> server

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

Are there any jQuery functions or plugins for comet on apache?

I have seen this question before and found this example in http://www.zeitoun.net/articles/comet_and_php/start which is really great and clear. However, it uses javascript.
My question is, are there any plugins, functions or something that would help me to implement PHP comet with jQuery easily? Because given example requires lots of javascript code.
And by the way, I want to use it on Apache. Is it possible?
If you are only doing long polling then jQuery will work fine. However, jQuery does not expose a readyState === 3 event, so there is no built in way to get data as it is streaming if that is the direction you want to go.
[Edit]
Here is the bug, #1172
And it looks like they added the functionality in 1.5, using a Prefilter
So yes, you can do all the comet stuff with jQuery now :)
Comet is long-polling where client sends a request and waits for the response from the server. The server queues the request and once it gets the updated results. It sends the response to the client.
So basically all you need to do is to send an .ajax request to the server and use the onSuccess callback to deal with the returning the data. The onSuccess callback will not be called unless the server gets the updated data.
Nothing really fancy at the client-side. The actual game is on the server side to queue the requests and then respond accordingly.
Take a look at this answer detailed code sample > How do I implement basic "Long Polling"?
i have made the jQuery version of comet before, this is what i had done:
var comet = {
connection : false,
iframediv : false,
initialize: function(){
// For other browser (Firefox...)
comet.connection = $('<iframe>');
comet.connection.attr('id', 'comet_iframe');
comet.connection.css( {
left : "-100px",
top : "-100px",
height : "1px",
width : "1px",
visibility : "hidden",
display : 'none'
})
//comet.iframediv = $('<iframe>');
comet.connection.attr('src', 'backend.php');
//comet.connection.append(comet.iframediv);
$('body').append(comet.connection);
},
// this function will be called from backend.php
printServerTime: function (time) {
console.log('time',time);
$('#content').html(time);
},
onUnload: function() {
if (comet.connection) {
comet.connection = false; // release the iframe to prevent problems with IE when reloading the page
}
}
}
$(window).load(comet.initialize)
.unload(comet.onUnload);
i had taken the code right off that page and made it jquery ^_^
there is a plugin i have seen, try this? http://code.google.com/p/jquerycomet/

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

Safe JavasScript that calls PHP script that calls external web service

I have a PHP page that needs to make a call to a external web service. This Web service call takes a bunch of sensitive data from a html form on the PHP page, e.g. SSN, and returns info related to that person.
The problem is that the web service call should be made as soon as the customer fills in the SSN field and the field loses focus, so the page cannot be reloaded in any way. I was thinking about using jQuery to make a call to the web service, but AJAX unfortunately requires that you are on the same domain as the requested resource. So I'm thinking about creating an local PHP page that makes the call to the web service and then use JQuery to call this new page.
Questions:
How do I use JQuery to call the local PHP script that makes the call to the web service?
Because the JQuery code will take sensitive data from a html form and send it to the PHP script, how can I encrypt the data?
To call your PHP file:
var url = "http://localhost/data.php";
var params = {
"SSN" : theSSN
};
$.get(url, params, function (){
// Do whatever you need here, once the data arrives.
});
To call the external webservice from PHP, I'd suggest using cURL.
To encrypt, I'd suggest using the HTTPS protocol instead of encrypting manually from JavaScript.
1) $.get("myscript.php", function(response) { alert(response) });
2) I wouldn't encrypt using jQuery, it would be slow and easy to decrypt. Enabling SSL on the server would be a better solution.
1: Ajax request example:
$.ajax(
{
type: "GET",
url: "http://yourdomain.com/yourpage.php",
success: function (msg) { //does something }
});
More details here
2: php XOR is a pretty good encryption algorithm, I use it myself for a project with sensitive data. you can find the function here.
Enjoy! :)
This probably won't help you in particular, but some webservices support something called JSONP, which adds a callback name to a normal JSON request.
However, chances are you will need to make some sort of local proxy, as not many JSONP services exist yet.
The way to go is enabling SSL on your domain, and doing the xmlHTTPRequest to the https of the remote service

Categories