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.
Related
I am having a table with data where I have an action button in last column to delete that particular row. I want to make the delete via ajax and without refreshing the page. I am using the following code but their is no response coming from the ajax page. Also the queries at the ajax page is not executing. Can I have some insight over what could be possibly wrong.
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var $tr = $(this).closest('tr');
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
success : function(response) {
if(response=='deletion success'){
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
}
}
});
}
return false;
});
});
</script>
And at delete_entry.php
<?php
header('Content-Type: application/json');
session_start();
require("../config.php");
require("../Database.class.php");
require("../site.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$fnc=new site_functions($db);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_ques","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_ques",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
if($db->query_update("tbl_ques", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
?>
Change your java script function as below
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
//changes from
success : function(response) {
if(response=='deletion success'){
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
}
});
//changes to
}
return false;
});
});
</script>
Also change you php file
<?php
header('Content-Type: application/json'); // Add this line its must
session_start();
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_question","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_question",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
//changes from
if($db->query_update("tbl_question", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
//changes to
?>
Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}
I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}
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);
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});