I am trying to retrieve all rows that are present within a table before the time the person has visited the page and there after update the div with any rows of data that has been added to the table since the user has been on the page.(Something like Whatsapp where the entire convo is visible and new messages get added to the bottom).
This is what I have so far using Ajax but I have no clue where I am going forward from this stage. It currently brings up only the newest record (IF I SET THE TIMESTAMP MANUALLY IN THE SECOND FILE) but not all the other records before it. Ideally I should work by posting the time to the second file.
How could I modify my code to get the functionality I desire?
Display (autoload.php)
var time = (new Date).getTime();
var interval = 1000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
$.ajax({
type: 'POST',
url: 'autoload2.php',
dataType: 'json',
data: 'time='+time,
success: function (data) {
$('.inner').append(data);
},
complete: function (data) {
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
Get data (autoload2.php)
$time = $_POST['time'];
$results = mysql_query("SELECT post_name FROM posts WHERE postime > $time limit 1");
$row = mysql_fetch_assoc($results);
$res = $row['post_name'];
echo json_encode($res);
Note: The time being used to query above doesn't work, only when it is hardcoded with the timestamp.
I think you need to move
var time = (new Date).getTime();
to your function
Because your time variable not changed
var interval = 1000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
var time = (new Date).getTime();
$.ajax({
type: 'POST',
url: 'autoload2.php',
dataType: 'json',
data: 'time='+time
}).done(function(response){
console.log(response);
});
}
setInterval(doAjax, interval);
In php:
$data = Array('name' => 'name of last row');
header('Content-Type: application/json');
echo json_encode($data);
Related
I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';
Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);
I am trying to create a textarea that automatically updates the database without the need to press a button or refresh the page. After a "keyup" occurs there will be a timer that will countdown for 2 seconds. If no other input is made within those 2 seconds then that the data should be updated in the database. If a input is made the timer will restart.
I've written the ajax code below, it doesn't seem to work.
$(document).ready(function() {
var timer;
$('#about').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#about").submit()
alert(value);
}, 2000);
});
var about = $('#about').val().trim();
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: about
},
success: function(response) {
$('#cid').val(response);
}
});
});
/* This is comment.php */
<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth_validate.php';
$cid = $_GET['customer_id'];
$about = $_POST['about'];
$sql = ("UPDATE patient_id SET about = ? WHERE id = ?;");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "si", $about, $cid);
mysqli_stmt_execute($stmt);
?>
Move the ajax into the timeout, rather than performing the submit, since you want to update with ajax.
$(document).ready(function() {
var timer;
$('#about').on('input', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
alert(value);
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: value
},
success: function(response) {
$('#cid').val(response);
}
});
}, 2000);
});
});
I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.
Firstly, I need to get every users lang and long.
At the moment, my code is only returning the last user in my database's lang and long.
This is my code for trying to return every clients long and langs:
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$username_ = $users_['username'];
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
}
Then I return this to my home PHP page using:
$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);
I recieve the AJAX request with the following JS / JQUERY code:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#lat').html(data['client_latitude']);
$('#long').html(data['client_longitude']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
And then finally, I try and display these in div's for testing.
Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.
But for now, It's not getting each users lang and long. Only the last user in my database's.
UPDATED CODE
The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?
I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.
My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).
This is my script in my main PHP file:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
$.ajax({
url: "includes/get_dash_map.php",
context: document.body,
type: 'POST',
data: {get_data_:true},
success: function(value_) {
const data_ = JSON.parse(value_);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${data_['client_latitude']}, ${data_['client_longitude']}`);
$parent.append($element);
}
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
My get_dash_map.php:
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}
echo json_encode($response);`
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = [
'client_latitude' => $client_latitude,
'client_longitude' => $client_longitude
];
}
echo json_encode($response);
You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
const data = JSON.parse(value);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
$parent.append($element);
}
}
})
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
with in the html
<div id="all-the-coordinates"></div>
Now I have two javascript, one is I called auto_refresh.js which I use ajax to continuously get new data from mysql database (This part is done).
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function()
{
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
}
}
})
}, 1000);
display.php
<div class="aside">
<?php
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
?>
</div>
ticketmanaget.inc
public function mainTicketSound()
{
$conn = DBManager::getConnection();
$query = "SELECT queue_id, ticket_name FROM queue
WHERE DATE(response_time) = DATE(NOW())
ORDER BY response_time DESC
LIMIT 1
";
$results = #$conn->query($query);
if ($results === FALSE or $results === NULL)
throw new DatabaseErrorException($conn->error);
if ($results->num_rows < 1)
{
$results->close();
}
else
{
while($rows = #$results->fetch_array())
{
$ticketname = $rows['ticket_name'];
return $ticketname;
}
}
}
audio function
var input = "<?php echo $ticket; ?>";
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[input[id]];
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
Then I have another script which is used to play audio files. Exactly which files to play is based on the new data get by ajax from database. In my case, I want my second script run the files based on the variable $ticket.
The audio script is done and run perfectly. However, it only play the sound when I refresh the page. I need it to run automatically when the auto_refresh.js get new data. Please help, thanks.
This might help "big picture".
Note that the code in display.php only runs one time - when page initially loads. You need that code to run each time new data is received.
Therefore, you must create a new php file that accepts via POST the new data, and returns (via echo not return) the desired $ticket value. Call this page as an AJAX call inside the success function of the first AJAX call. Something like this:
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function(){
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
$.ajax({
url: 'new_php_file.php',
type: 'post',
data: mainDisplayData,
success: function(axData){
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
//below element already exists. You should update it rather than creating another
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[axData[id]]; //axData returned by AJAX
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
}
});
}
}
});
}, 1000);
new_php_file.php
<?php
$new_data = $_POST['mainDisplayData'];
//insert code required to run lines that follow, and/or modify as required
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
echo $ticket;
Call the sound playing function in the other script in this block:
if(mainDisplayData !== mainDisplayCacheData){
// e.g. otherScriptFunction();
}
On the Server-side: You should echo the "$ticket" variable.
On the Client-side: Call your sound playing function inside the 'success' ajax callback:
if(mainDisplayData !== mainDisplayCacheData){
PLAY_SOUND(mainDisplayData);
}