Jquery + Ajax is not working properly, why? - php

This code will show a counter when there's rows with the status = unread, and it will UPDATE the row to status = read when the user click on the a icon <i class="fas fa-bell"></i>.
The problem is: This is not working propelly, when i click on the <i class="fas fa-bell"></i> it get a delay of 3-9 seconds to update the counter to 0, it update my table instantly, only the counter that get some delay, but sometimes i need to reload the page and click on the icon to update my table, why? What's wrong?
html:
<span class="text-white divCountNT" id="datacount"></span>
script:
<script>
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 10000);
});
$(document).on('click', '.fa-bell', function (){
$.ajax({
type: "POST",
url: "update.php"
});
});
</script>
select.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
if($countNT >= 1){
echo $countNT;
}
?>
update.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
?>

You dont have a callback function for your ajax call so your table only updates itself with load function. Your ajax call should be something like that :
$.ajax({
type: "POST",
url: "update.php"
}).done(function() {
window.location.reload(true);
});

You can Try with this code It's Working Fine
$.ajax({
type: "POST",
url: "update.php"
success: function(result){
$(body).find("#loadData").html(result);
// $(body).find("#loadData").append(result); //you can also use for append data insted of replace
}
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
check this for use of more methods of AJAX https://www.w3schools.com/jquery/ajax_ajax.asp

Related

AJAX SET INTERVAL

I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);

AJAX/Jquery not deleting row from MySQL table

I am trying to use AJAX and jQuery to delete a record from a table. The row is being removed from the page view as required, but not from the table.
Im using the following files and related sections:
Query
$result = mysql_query("SELECT id,name FROM myTable");
Query result:
while($row = mysql_fetch_array($result))
{
$id1=$row['id'];
$dataname=$row['name'];
?>
<div class="show">
<span class="name"><?php echo $dataname; ?></span><br><span class="name"><?php echo $id1; ?></span>
<span class="action">Delete</span>
</div>
<?php
}
?>
AJAX Script
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
delete.php
<?php
include('db.php');
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
mysql_query($delete);
}
?>
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
You are using $id1 in the delete statement, it should be $id
$delete = "DELETE FROM `testdb` WHERE id = '$id'";
NOTE : Your code is vulnerable to sql injection, start using
preparedStatement with mysqli_ or PDO
UPDATE: Using PDO to do the delete operation
error_reporting(E_ALL);
ini_set('display_errors', '1');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', '****', '****');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$id = $_POST['id'] ;
$sql = "DELETE FROM testdb WHERE id = :id ";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

Profile view counter - variable showing as null despite being declared and used elsewhere

I'm trying to build a profile view counter with PHP and jquery ajax. I want the page count to be fetched, and incremented and input into the database when the page is loaded.
Here is my jquery:
var views = "<?php echo $views;?>";
$(document).ready(function(){
view = parseInt(views) + 1;
$.ajax({
url: "user.php",
type: "POST",
data: {
'views' : view //array of objects
},
success:function(data, response){
console.log(data);
alert(view);
}
});
and the php that picks up the ajax:
if(isset($_GET["id"]) && isset($_GET['activ'])){
$activ = preg_replace('#[^0-2]#i', '', $_GET['activ']);
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
} else {
header("location: http://www.unlimitedtutors.com");
exit();
}
if (isset($_POST['views'])){
$views = mysql_real_escape_string($_POST['views']);
$views = intval($views);
$sql1 = "UPDATE users SET views='$views' WHERE id='$id' LIMIT 1";
$query1 = mysqli_query($db_conx, $sql1);
echo $id;
}
the problem is that the $id variable doesnt seem to be showing up although I know it's been declared. This obviously means that the sql is not working correctly. Does anyone have any suggestions?

Reload a div only if there is new data

If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.

How to instantly display data after form submission using jQuery and AJAX?

I have a PHP form that uses jQuery/AJAX to submit data into a MySQL database table. Currently, I have a message display saying " Done!" once the form is submitted, but would like the actual data to instantly display after it has been submitted. I have a loop setup to display previously added messages in divs with the class name 'msg_container', and would like the new data to display in one of these divs after form submission.
What is the best way to do this? Any help would be greatly appreciated!
index.php javascript
<script type="text/javascript">
$(document).ready(function () {
$(".button").click(function () {
var user_id = $("textarea#uer_id").val();
var msg = $("textarea#msg ").val();
var dataString = 'user_id=' + user_id + '&msg=' + msg;
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function () {
alert("Done!")
}
});
return false
});
});
</script>
index.php query
$user_id = $_GET['user_id'];
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$sth = $dbh->query ("SELECT *, user.last_name, user.first_name FROM msgs
INNER JOIN users
ON msgs.user_id = users.id
WHERE user_id = '$user_id'
ORDER BY timestamp");
$row = $sth->fetch ();
index.php HTML
<div id="msgs">
<?php while ($row = $sth->fetch ()) { ?>
<div class="msg_container">
<div class="left"><? echo $row['last_name'].', '.$row['first_name']; ?><br />
<? $timestamp = date('m/d/Y g:i a', strtotime($row['timestamp'])); echo $timestamp; ?>
</div>
<div class="right"><? echo $row['msg']; ?></div>
<div class="clear"></div>
</div>
<? } ?>
<div class="add_note">
<div class="left">Add Message</div>
<div class="right">
<form id="add_msg">
<textarea id="msg" name="msg"></textarea>
<input type='submit' class="button right-aligned" value='Submit' />
</form>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
add.php
<?php
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$user_id = $_POST['user_id'];
$msg= $_POST['msg'];
date_default_timezone_set("UTC");
$timestamp = date('Y-m-d H:i:s', strftime(gmmktime()));
date_default_timezone_set($_SESSION['TIME_ZONE']);
$sth = $dbh->prepare ("INSERT INTO msgs (id, user_id, msg, timestamp) VALUES (?, ?, ?, ?)");
$data = array (NULL, $user_id, $msg, $timestamp);
$sth->execute ($data);
session_write_close();
?>
You could just append the new message after the previous ones. Something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + lastNameVariable + ', ' + firstNameVariable +
'<br />' + timeStampVariable +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
You will need to put the first name, last name, timestamp, etc. into variables (or do it a different way, like do an AJAX call to get the info - whatever you prefer). I didn't know what user_id is so I just thought I would let you fill in those variables.
This is just the basic idea of what you could do. If you have any questions, just ask.
I hope this helps.
Edit:
If you created another page called "getname.php" or something like that (to get the first and last name) that would display "first name, last name" based on the user ID passed in the URL, that could work. In the URL it could have ?user_id=1234567 and then on that page, it would do a mysql_query and display the first and last name. This is what I would do:
getname.php ↓
<?
// ...
$user_id = $_GET['user_id'];
$result = mysql_query("SELECT * FROM table WHERE user_id = '$user_id' AND ...");
$row = mysql_fetch_array($result);
// ...
echo $row['last_name'] . ', ' . $row['first_name'];
// ...
?>
Of course you would do this the way you do your queries, but hopefully this helps you understand what I'm saying. Then, after you have that, you can do:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
var firstAndLast = '';
var theTime =
$.get('getname.php?user_id='+user_id, function(data) {
firstAndLast = data;
});
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + firstAndLast // this will display: "first name, last name" because of getname.php
+ '<br />' + theTime +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
As for the time, you could either display it with JavaScript (when they refresh it would show the time that was recorded by PHP) or do the same as you did for name.
Consider the jQuery ajax method load. This is a higher level version of ajax. You will send your request and the response will immediately be placed into the preceding selector elements.
$('#result').load('ajax/test.html', data);
Here's just a quick idea to get you going. You need to return the data from the script you call with AJAX; a data that you would use to generate the DIV you want. You'll also need to change the ajax call to something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(data) {
console.log(data); //to see what's returned
//use the data to generate content you want
alert ("Done!")
}
});
Due to the structure of your data, it might be the best to send a JSON response.
In the success part add this code:
success: function(data){
$('#flash').css("display","block");;
setTimeout(function () {
$('#flash').slideUp();`enter code here`}, 2000);
}
In the HTML add this code:
<div id="flash" style="display:none;">Data Saved Successfully</div>

Categories