AJAX action with cron-job? - php

I tried to update so much rows with PHP that I had to make it with ajax (becouse execution time in server is too short for execute all rows). So I made a code which should call a .php file with the code inside, which updates sended ROW id in mysql table.
I have a code
<html>
<head>
<title>Cron job!</title>
<meta charset="UTF-8" />
<script src="jquery.js"></script>
</head>
<html>
<body>
<div id="body">
</div>
<script>
$(document).ready(function(){
var array_items = <?=$table_info?>;
var updated_items = 0;
for(var i=0; i<array_items.length; i++){
// pradedam kreipimąsi į kiekvieną rową jo updeitui su ajax
$.ajax({
url: "ajax_cron.php",
type: 'POST',
dataType: 'json',
data: {update_id : array_items[i]['ids']},
success: function (data) {
// kreipimąsis pavyko
if(data.updated_id){
updated_items += 1;
}
$("#body").html(updated_items + " iš " +array_items.length + " updeitinta sėkmingai");
}, error: function(e){
console.log(e.message);
}
});
}
});
</script>
</body>
</html>
and it works when I open url with browser but when I make a call to this script with CRON JOB - ajax doesn't work.. So how to make it work?

Ajax is a client side technology, so it requires client (a browser) to be able to execute the script and most importantly the DOM elements which could be read by your Javascript.
Cron Job on the other hand runs on CLI which does not know anything about the DOM when a script runs there.
So in other words what you are trying to do is not possible with the current web technology that we have. However you can always run a server side script on cronjob but client side script, no you can not.

Related

Ajax, JQuery, GET request with PHP error

I have a very basic webpage which contains of two files, phpcode.php.cgi and frontpage.php.cgi.
I have dropdowns that should be populated dynamically, however I can't get the request/reponse to work. The ID of the dropdown is "start".
I have an Ajax request in the frontpage file:
$(document).ready(function () {
$("#start").change(function(){
alert("dropdown changed");
var val = $('#start').val();
$.ajax({
type: "GET",
data: {Station_Nr : val},
url: "phpcode.php.cgi",
success: function(data){
alert(data);
}
});
});
});
and my phpfile looks like this:
<?php
if(isset($_GET['Station_Nr'])) {
echo "it works";
};
?>
It tries to request from url../phpcode.php.cgi?Station_Nr=27
When I try to enter the page I get a 500 error.
According to chrome, the error lies in the row which starts with $.ajax.
I have included:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Thanks!
In the top of the file is #!/usr/bin/php5 located.
Here was \r\n added because of Windows and the transfer method was binary. The Apache server responded with an error and when replacing \r\n with \n it works.
When you obtain a 500 error is because something is wrong in server not in client, use /phpcode.php.cgi in $.ajax to use an absolute path just in case.

How to check data from mysql realtime using ajax post requests?

How to check data from mysql realtime using ajax post requests ?
I use this code for check in mysql , if user have a new message it's will be echo YOU HAVE NEW MESSAGE text on realtime.
and this code will post to get_data.php every 1 sec , i think it's very work hard for server and client ,
when i try it's not work, How can i do that ?
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<form id="idForm"/>
<input name="uid" value="1234"/>
</form>
<div id="result_data"></div>
<script type="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
type: "POST",
url: get_data.php,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
$('#result_data').show();
}
});
},1000);
});
</script>
Your best practice would be to go with WebSockets.
The protocol overhead is much smaller than HTTP and you will play PING and PONG with the server to check for new data.
With websockets your client could send a message by emitting data your server would receive this and e.g. broadcast it out to other clients.
Try to get your head in Socket.io that is what I did to understand this ;)
Asumming your php file is correct, it might help if you wait for your document to be ready in your javascript
$(document).ready(function(){
//Your code
});
It's a minor thing but sometimes it break scripts

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

Imitate opening a page in a browser so that ajax can run on a server when scheduled as a cron job

I have scheduled a cron job that runs and its supposed to execute some ajax call but it does not. The page it renders is similar to the one below. i cant execute each script one by one and wait for the responses but because they all keep long, i need to do them asynchronously. When i open this page on my localhost, it renders the html below, runs perfectly and starts the other instances through ajax. But wen i put it on my online server and start it through curl as a cron, the ajax does not run, the page only renders.
<html lang="en">
<head>
<script type="text/javascript" src="./assets/jquery.js"></script>
</head>
<body>
//execute some php here
<script>
var numberOfInstances = "4";
var userId = ["82372","93823","28372","39823"];
//Ajax call to url that is supposed to run for each user id
function startAnotherInstance(i){
$.ajax({
url: "./getreplies.php?instance="+i+"&userid="+userId[i],
type: 'GET',
data: null,
success: function() {
}
});
}
//Initialize the number of instances
for (i=0;i<numberOfInstances;i++){
startAnotherInstance(i);
}
</script>
</body>
That's because the Javascript engine is built into your browser. CURL does not know what Javascript is.
What you need to write is called a "shell script" that can be initiated with a cron task.

Facebook auto-refresh

What technology does Facebook use to auto-update information on a page without reloading it?
For example, while someone is viewing his profile if he receives a new message the inbox number auto-updates in the top bar. Same with wall posts, etc. Code-wise how is this managed?
They are using several new technologies like AJAX and History API.
I strongly recommend you to use jQuery or another framework for AJAX and History.js for the History API.
the core javascript function set_timeout() is the man! Every x seconds the server is queried to fetch new results, updates etc. FB uses AJAX to get the info from the server and JS to update the page.
Facebook open a connection using AJAX which then hangs and hangs. The server doesn't send anything or respond to your browser unless, of course, a notification. Eventually, your browser may give up and disconnect from Facebook in which case the javascript will create a new connection and the process continues.
This is superior to polling the server every few seconds as it reduces load and makes load more predictable too.
Here's more info: http://en.wikipedia.org/wiki/Comet_%28programming%29
use setInterval on a function which makes an Ajax call to a file in which you have a MySQL query which checks something.
setInterval( "refresh();", 60000 );
refresh = function(){
var URL = "file.php";
$.ajax({ type: "GET",
url: URL,
succes: function(data){
if(data){
//change stuff
}
}
});
}
that should be a good starting point
coba gunakan script ini..
autocallajax.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
<div id='sample'>100 </div>";
?>
</body>
</html
load.php
<?php
mysql_connect("localhost","root","siantarman");
mysql_select_db("konsultasi") or die("<br><br><hr width=350 size=1 align=left>
<font color=red><b>Database belum tersambung!</font></b>
<br>Hubungi administrator anda!<br>" . mysql_error());
$sql_info=mysql_query("select jumlah from data_konsultasi where id = '9'");
$r_data=mysql_fetch_array($sql_info);
echo"$r_data[jumlah]";
?>
selamat mencoba..

Categories