Ajax update textarea without button or page refresh - javascript

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);
});
});

Related

Update image after it's been clicked, without reloading page

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>
';

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

Cannot change php session variable by javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
MY php code is below:
public function checkWhetherASalaryProcessIsOngoing(){
if(isset($this->session->userdata['salary_is_on_going'])){
echo $this->session->userdata['salary_is_on_going']; }else{echo 'NOTSET';}
}
public function set_salary_is_on_going(){
if(!isset($this->session->userdata['salary_is_on_going'])){$isset = $this->session->set_userdata('salary_is_on_going','SET');}
echo $this->session->userdata['salary_is_on_going'];
}
public function delete_set_salary_is_on_going(){
$this->session->set_userdata('salary_is_on_going','NOTSET');
echo $this->session->userdata['salary_is_on_going'];
}
My javascript code:
$(document).on('click','a#process',function(){
// set the start time
t0 = performance.now();
alert('<?php if(isset($this->session->userdata['salary_is_on_going'])){echo $this->session->userdata['salary_is_on_going'];}?>');
var payment_period_id = parseInt($('#paymentPeriodId').val());
var unit_id = parseInt($('#unitIdz').val());
var user_id = parseInt($('#userIdz').val());
// check whether same session variables exists in all opened pages. function in D:\xampp\htdocs\diganta\assets\js\common_js.php
checkSessionDataWithPageSessionData(function(dataii){
if(dataii === 'NOTCHANGED'){
checkWhetherASalaryProcessIsOngoing(function(dataoo){
if(dataoo === 'NOTSET'){
// if not set then set session variable named salary_is_on_going
set_salary_is_on_going(function(data55){
if(data55 === 'SET'){
progress();
var checkedRows = [];
$("#supervisorList tr").each(function () {
if ($(this).find("input").is(":checked")) {
checkedRows.push({"supervisor_id" : $(this).find("td:eq(1)").text()});
}
});
if(checkedRows.length < 1){
delete_set_salary_is_on_going();
custom_alert('Supervisor not selected.',"Error",10,'right',50);
}
if(checkedRows.length > 0){
ensureItIsNotARevisedSalary(checkedRows,user_id,unit_id,payment_period_id);
}else{return;}
}else{custom_alert('Can not set salary ongoing session variable.',"Error",10,'right',50);return;}
});
}else{custom_alert('A salary process is ongoing.',"Error",10,'right',50);return;}
});
}else{custom_alert('session data change detected. Cannot Execute.<br><br> refresh.',"Error",10,'right',50);return;}
});
});
function ensureItIsNotARevisedSalary(checkedRows,user_id,unit_id,payment_period_id){
var url = '<?php echo base_url();?>primary_salary_processing/ensureItIsNotARevisedSalary';
$.post(url,{payment_period_id:payment_period_id}).done(function(data){
data = parseInt(data);
if(data > 0){
setTimeout(function(data){delete_set_salary_is_on_going();},1000);
custom_alert('This is a revised salary it can not be processed from here.',"Error",120,'right',50);
}
else{checkWhetherSalaryIsLocked(checkedRows,user_id,unit_id,payment_period_id);}
});
}
function checkWhetherASalaryProcessIsOngoing(result){
var url = '<?php echo base_url();?>primary_salary_processing/checkWhetherASalaryProcessIsOngoing';
$.ajax({
url:url,
data:{},
type:"POST",
success:function(data){
result(data);
},
});
}
function set_salary_is_on_going(result){
var url = '<?php echo base_url();?>primary_salary_processing/set_salary_is_on_going';
$.ajax({
url:url,
data:{},
type:"POST",
success:function(data){
result(data);
},
});
}
function delete_set_salary_is_on_going(){
var url = '<?php echo base_url();?>primary_salary_processing/delete_set_salary_is_on_going';
$.ajax({
url:url,
data:{'url2':'<?php echo $this->session->userdata['url'];?>'},
type:"POST",
success:function(data){
},
});
}
After clicking a#process the salary process starts.
The problem is javascript function delete_set_salary_is_on_going() cannot change
session variable having index of 'salary_is_on_going' to 'NOTSET'
Did you forget to write session_start() in your receiving/processing url?
<?php session_start() ?>

Opencart Ajax filter For products

The filter contained Refine search button and the page loads the product according to search.But I want when i check the checkbox the product should display.This can be acheived by ajax..
Original script Of opencart 2.1.0.2 product filter
`<script type="text/javascript"><!--
$('#button-filter').on('click', function() {
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
});
//--></script>
`
And I tried using ajax
`$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
$('.products-block').html(data);
}
});
console.log;
return false;
});`
I am getting the desired result .But It loads the whole page. And how can i use any loader if possible.
location is global and changes the browser url. To avoid using global location you need to define location using var
$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
var location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
$('.products-block').html(data);
}
});
console.log;
return false;
});
It was just little change in code.In success function i removed the specific id and its working fine
<script type="text/javascript">
$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
html(data);
}
});
console.log;
return false;
});

How do I return the new count of record?

I have a notification functionality, and it updates in the table when read/viewed.
What i have is a list of li of the notifications & when the button was clicked it calls the ajax function to mark it as read, however my problem is how can I update the counter in the page since it count only for the notifications that wasn't read yet.
my js code is here:
<script type="text/javascript">
$(function() {
$(".confirm").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
var closest_li = $(this).closest('li');
$.ajax({
type: "POST",
url: "mark_read.php",
data: dataString,
cache: false,
beforeSend: function() {
closest_li.animate({'backgroundColor':'#fb6c6c'},300).animate({ opacity: 0.35 }, "fast");;
},
success: function() {
closest_li.slideUp('fast', function() {$(this).remove();});
}
});
return false;
});
});
And here is the file content of the mark_read.php
<?php
if(isset($_POST['id'])) {
$id = $_POST['id'];
$id = mysqli_real_escape_string( connect(), $id );
$result = query("UPDATE tbl_notifications SET log_stat='1' WHERE log_id='$id'");
}
?>
and my counter is a label that echoes the php sql query of count num rows.

Categories

Resources