Executing AJAX written in a PHP script with cron - javascript

I've written a PHP script that reads data from Facebook user's profile and sends it to my server through AJAX. This script needs to run in intervals, so I added a cron. All the PHP functions and interactions with databases through MySQL are working with cron. But AJAX is not. I know it's (JavaScript) a client-side script, but is there any other way? How I can execute JavaScript (AJAX) written in a file through cron.

Ajax is a client-side technology you cannot run that in PHP console.

Ajax calls consist of an API (application programming interface). The API is the system of calls through which a client (the browser) communicates with a server (the server).
In your case, the client is the computer on which the PHP script is running and the server is your server. If you can replicate the API used in JavaScript in PHP then you are away on hack.
For example, suppose the sever you were communicating with had a service called "postupdate.php" and it took one value called "update", the API call might look like this in JavaScript:
<script type="text/javascript">
var response;
$.ajax({
url: "http://www.example.com/postupdate.php?update=This_is_my_update"
}).success(function(text) {
response = text;
});
</script>
The same API call might look like this in PHP:
<?php
$response = file_get_contents("http://www.example.com/postupdate.php?update=This_is_my_update")
?>
This example assumes the API uses the HTTP GET method. APIs that use HTTP POST methods are more complicated but can be used in PHP as well.

Related

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 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?

Call Python Script from Javascript

I am on a dreamhost server and have some HTML that calls some javascript when a button is pressed. I am trying to call a python script when this button is tapped.
First off, to my knowledge as I am on a shared host I cannot use AJAX as it is not supported, so I need to do this without AJAX. Right now I am trying to do a XMLHttpRequest which is working.
I also realize doing an XMLHttpRequest is not the best way since the files are both on the server there must be a way to just call the file directly?
So if someone call tell me how to call it directly or help me fix this error in the browser console that would be great.
Thanks for the help
EDIT
I have an HTML file when a user taps a button on this file it calls some javascript that is in the HTML file. This javascript currently makes a POST Request, to a python script that is on the same server and the HTML file.
What I want instead of making a post request to the python file that is on the server, I want to just directly call the python file, from the javascript that runs, when the button the clicked in the HTML file.
Both the HTML file which contains the javascript and the python file are on the same server. And I don't want the python to run in the browser, I want it to run in the background on the server.
How can I use the Javascript to call this python file?
As far as I understand your question what you are looking to do is called a "remote procedure call", or some sort of Service Oriented Architecture (SOA).
You are on a right track in making a POST request to the server.
You can setup a middleware like flask, or cherrypy to run the script when you send a GET, PUT, POST ... request. And inside of the middleware controller you can call your script.
Basically you have started to create a RESTful api, and its a pretty standard way these days to run logic on the backend.
Some examples of different frameworks for doing url routing:
Python:
CherryPy: http://docs.cherrypy.org/en/latest/tutorials.html#tutorial-9-data-is-all-my-life
Flask: http://flask.pocoo.org/docs/0.10/quickstart/
a longer list of lower level python: http://wsgi.readthedocs.org/en/latest/libraries.html
NodeJs:
Express: http://expressjs.com/guide/routing.html
Koa: https://github.com/koajs/route
Hapi: http://hapijs.com/tutorials/routing
Also very good is this question: JSON, REST, SOAP, WSDL, and SOA: How do they all link together
Another way that you could do this from the browser would be to use sockets, which opens a connection between the client and the server.
Inside the javscript you could use socketio:
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.connect('http://localhost:8000')
socket.emit('run_a_script_event', {arg1: 'hello', arg2: 'world'});
</script>
And in your python code you could use the socketio client for python (https://pypi.python.org/pypi/socketIO-client):
from your_module import thescript
from socketIO_client import SocketIO, LoggingNamespace
def run_a_script(*args):
print('arg1 and arg2', args)
thescript()
socketIO = SocketIO('localhost', 8000, LoggingNamespace)
socketIO.on('run_a_script_event', run_a_script)
Looks like there is also a version specifically for flask: https://flask-socketio.readthedocs.org/en/latest/
Or you could run the python directly in the browser by converting it to javascript with a transpiler:
http://www.skulpt.org/
Or you could use node javascript to spawn a child process which runs the python script:
https://stackoverflow.com/a/20973067/2026508
Or you can import the python script into node like:
Use of node-python to execute python scripts from web application hosted under python?

How can I call javascript function in Model or Controller in Cakephp?

I have to call a javascript function from my Model or Controller. I can call it from the view file but how can I call a JS function directly from Model.
Is there a way to do that?
PHP is a server side language. This means the PHP file will get processed on the HTTP server and then deliver the generated HTML page to the client.
Javascript (JS) is interpreted on the the client (browser) and interfaces with the HTML and other remote resources.
Due to this model, PHP and JS know nothing about each other. So to call JS directly from the PHP file is not possible.
If you are looking to make a client browser call a JS function and the PHP script defines the values for the JS function you can use echo() and some string concatenation
//this is an example and will not run.
echo "<script>myJsFunction('" . $arg1 . "','" . $arg2 . "')</script>";
This will embed the JS function call in the HTML page returned to the client. Once the client renders the HTML page it will execute the function call as it comes across it.
If you could give an example of what you trying to do I might be able to give you a more accurate answer.
For a deeper explanation of the client server architecture and where things get executed have a look at Web Browser Client Server Architecture
No, try understanding the MVC pattern, the idea is that the model is not aware of the view and doesn't have to be. Also you can't call JS with php, which is a server side language and doesn't know anything about the client side scripts.
What you want is to implement long polling. I recommend you to learn and read about the basic technologies involved before trying to implement something.
http://en.wikipedia.org/wiki/Push_technology
http://en.wikipedia.org/wiki/Comet_%28programming%29

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