how to execute a PHP code periodically using AJAX? - php

I would like to know how to execute a PHP code periodically (for example every 5 seconds) using AJAX. This is the PHP code that I want to execute periodically:
<?php
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)){
echo "a new event was added";
}
?>
In fact, I am started in AJAX so is there anyone who can provide me a simple example about how to do that?

Do you know what exactly is AJAX?
It looks like you will be using a library for this, so take a read here: http://api.jquery.com/jquery.ajax/
If you are not planning to use jQuery, you could check this XMLHttpRequest project that is cross-browser: https://github.com/ilinsky/xmlhttprequest
Make use of AJAX periodically using a setInterval of 5 seconds where you would make a call to a PHP file you have in your server that would run the code you specified.
Take the following example:
index.html
setInterval(function() {
$.get("file.php", function (data) {
console.log('Good to go, data was loaded');
console.log(data);
});
}, 5000);
file.php
<?php
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)){
echo "a new event was added";
}
?>

You can use an interval and jQuery get() function:
var myInterval = setInterval(function() {
$.get( "(YOUR URL)", function( data ) {
alert( "Load was performed." );
});
}, 5000);

Related

jQuery datatable large dataset delay

My jQuery datatable is taking a little too long to display some data.
The query is simple. In the database, running the same query returns the same results in microseconds, regardless of size.
Here is how the query looks in my PHP script:
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$out = array();
while($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
?>
Most of the data returned is less than 1000 records. But there are a few that return more than 10K to 20K records.
This causes a delay in which if the user is using Firefox, they will receive the "A web page is slowing down your browser. What would you like to do?" error message where they have to select 'Stop' or 'Wait'.
Back in my jQuery, here is how I'm sending the parameter to the PHP script:
$('#commoditySelect').on('change', function()
{
var commodity = $('#commoditySelect').val();
$.post('api/searchKeyComms.php', {commodity:commodity}, function(data)
{
var table = $('#example1').DataTable();
table.clear();
table.search('').draw();
var obj = JSON.parse(data);
obj.forEach(function(item)
{
table.row.add([item.COMM_CODE, item.KEY_COMM, item.MOD_DATE, item.MOD_USER]);
});
table.draw();
});
});
On the main HTML page, near the bottom, I set the datatable like this:
$('#example1').DataTable({
"dataType": "json",
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
Is there anything that I can add/change to any of the code above that will improve the performance of the rendering of the datatable?
I found this page: https://datatables.net/forums/discussion/2651/alternative-server-side-php-script
But I am not doing any concatenations. As stated above, it's a simple query that I'm using, and in the database, the data is returned quickly.
I even found this page: rendering large server-side datasets in jquery datatables
But the only thing I got from that page is that datatables are not made for large datasets. 20K doesn't seem too large.
Why loop on your $out array since your $row is already an associative array.. No need to loop.. ^_^
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$row = $query->fetch_assoc()
echo json_encode($row);
?>

Error with my dojo ajax php request

Im trying to use a dojo ajax function to call a PHP file that then returns the contents of a DB table in JSON format.
My function:
var _getWeatherInfo = function(){
dojo.xhrget({
url: "PHP/weather.php?ntown=" + _ntown,
handleAs: "json",
timeout: 5000,
load: function(responce, details) {
_updateWeathertData
},
error: function(error_msg, details) {
_handleError(error_msg);
}
});
}
My PHP:
<?php include('configHome.php'); ?>
<?php
$ntown = $_GET['ntown'];
$weather = array();
$query="SELECT * FROM `weather` WHERE `town` = '$ntown'";
$result=mysql_query($query);
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
echo json_encode($weather);
mysql_close();
?>
When using this code I am getting an error message saying that "$ntown = $_GET['ntown'];" is an undefined index. I have tried removing the index all together and using an actual value in the select statement (i.e. SELECT * FROM weather WHERE town = 'Auckland') but all I get back is the value i enter ["Auckland"], and not the 3 other values that are meant to be returned, ["Auckland", "Sunny", "8", "14"].
Any ideas? I can try add more info if needed. Thanks!
There are some other issues with your code, but to get to the one you are asking the question about. You have this:
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
What you are doing is just taking the first value of the row (of which there is probably only one, and just sending that back. This is what you need:
$weather = mysql_fetch_row($result);

Make A Next Button For More More Data?

Hi dear friends,
I hope u are all fine.
I want to make a next button for getting more data from mysql database.
For example:
$sql = mysql_query("SELECT * FROM table LIMIT 0,7");
It get 7 rows.For next data code is that.
$sql = mysql_query("SELECT * FROM table LIMIT 7,7");
I can i do that using ajax.
As you can see in many website like facebook,When you click on comment it give a limited
comment and when you click on more comment it give more and so on.In this proccess you can see
that the other content of page does not change.It means it can use ajax and how can I do that in ajax.
Please help me.Thanks.
your ajax would be something like this
var numberOfdata = 0;
$('#button').click(function () {
$.ajax({
url: 'load.php',
data: {
'limit' : numberOfdata,
// other data ...
},
type : 'post',
// other parameters...
}).success(function (data) {
// adding data to your website
numberOfdata += 7;
});
});
and in your server side, you could do something like this
... other operations
mysql_query("SELECT * FROM table LIMIT " . $_POST['limit'] . ",7");
... continuting the work
Note: You should be able to handle SQL injections on your own.
Edit: please note that mysql_query is not recommended.
You have to send the current comments count via Ajax, get the new ones from the response and display them.
Javascript:
$(document).ready(function() {
$('a.pagination-more').click(function() {
var current_comments_count = $(this).data("current_comments_count");
$.ajax({
type: "POST",
url: "pagination/pagination_ajax_more.php",
data: { "limit_start":current_comments_count },
beforeSend: function() {
$('a.pagination-more').html('<img class="loading-gif" src="pagination/loading.gif" />');
},
success: function(html){
$("#more").remove(); // This is the "More" button. It is appended to the end again in the 'html' variable
$("ul#updates").append(html);
if($("a#end")[0]) {
$("div#more").remove();
}
}
});
return false;
});
});
On the PHP side you just get $limit_start, get results from the database and echo the html like:
$limit_start = $_POST['limit_start'];
$query = mysql_query("SELECT COUNT(*) FROM `table` LIMIT 0, $limit_start");
$current_comments_count = mysql_num_rows($query);
$query = mysql_query("SELECT * FROM `table` LIMIT $limit_start, 7");
while($row = mysql_fetch_assoc($query)) {
echo '<li>
blah blah...
</li>';
}
if(mysql_num_rows($query) == 7)
echo '<div id="more"><a data-current_comments_count="$current_comments_count" class="button pagination-more" href="#">More</a></div>';
else
echo '<div id="more"><a id="end" class="button pagination-more" href="#">The button will be removed from jQuery...</a></div>';
Of course it is strongly recommended to secure your application and not to use only mysql_query(). This code is working but I removed some other stuff and didn't test it now. So, some errors may occur.

Ajax Printing Database Records to Multiple Fields

I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.

Only get new data from PHP file - jQuery

Instead of reloading old data from a PHP file that I parse with JavaScript using JSON, I want to ONLY load new data. My project is a little multiplayer environment and my goal is to have all users see either other move in realtime.
Here is my code:
JavaScript:
function getUsers() {
$.get("database/getData.php", function(data) {
// data returned from server;
for(var i = 0; i < data.response.length; i++) {
// users obtained from the array... parse them now
var user = data.response[i].split(" ");
// user info
var id = user[0];
var username = user[1];
var xx = user[2];
var yy = user[3];
userCount = data.response.length;
$(".online").html(userCount + " users online right now.")
// position the users
moveCharacter(username, xx, yy);
}
}, "json");
}
var infoGetter = setInterval(getUsers, 2000); // we may need to improve this... type of realtime
And here is my PHP:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
How can I make it so ONLY new data from the PHP file is parsed by the JavaScript instead of all data?
Thanks!
I would suggest you to modify the select query. Instead of having it as select * from users, add some where condition like where userId > somenumber. Now send the last userId which we processed in the last request along with next request which you make from client side. This will make sure that you will always gets new response.
Indeed, with your current setup, every call to "getUsers" will replay the entire state of the game up to the last move made, and not necessarily finish in the correct state. In order to get the behavior you want, you will need to add a timestamp or serial id to the "users" table and then order your results in order to get the most recent moves. You will need to do this for each user separately, so you will also need to provide a mechanism to retrieve and iterate through all users...
Thus your javascript becomes something like...
function getUsers() {
$.get("database/getAllUsers.php", function(data) {
$.each(data, function(i,uid) {
$.get("database/getData.php?uid=".uid, function(data) {
...
and your php query becomes...
$query = "SELECT * FROM users WHERE uid=$_GET['uid'] ORDER BY timestamp DESC LIMIT 1

Categories