chatting system between users - php

I have been trying to create a chatting system using php+ ajax + mysql.
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name'];
?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function() {
var id = $(this).data("id1");
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: id
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
}
});
}
fetch_chat();
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: id,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
});
});
but the trouble is that when I try to insert a new message in mysql the messages is send to all the users in which i have clicked.
the fetch_chat.php
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="select * from chats where user_from='$_SESSION[name]' AND
user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to'
order by id";
$res1=mysqli_query($con,$sql1);
if(mysqli_num_rows($res1)>0){
while($row=mysqli_fetch_array($res1)){
?>
<b> <?php echo $row['user_from']; ?>:</b>
<?php echo $row['msg']; ?><br /><br />
<?php
}
}
else
echo "No msgs <br />";
?>
</body>
</html>
and insert_chat.php is:
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$msg=$_POST['msg'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="insert into chats(user_from,user_to,msg)
values('$_SESSION[name]','$user_to','$msg')";
$res1=mysqli_query($con,$sql1);
if($res1){
?>
<b> <?php echo $_SESSION['name']; ?>:</b>
<?php echo $msg; ?><br /><br />
<?php
}
?>
</body>
</html>
I don't know where I am going wrong. Please help me with this.
For example, the list of users is:
(1) user a
(2) user b
(3) user c
So at first I clicked a then I changed my mind to select b and send the text. But there arises the problem: the data gets inserted for both a and b like I am texting both of them at the same time.

You keep on adding more and more "click" event handlers to "sub", every time you click on "first_name". So then each time you click sub again, it runs all the previous event handlers again and again. So you get the current message, but sent to all users you previously clicked on since you loaded the page.
$("#sub").click(function() {
needs to be
$("#sub").off("click").on("click", function() {
so that it removes previous handlers before you define the new version with new data.

Related

AJAX loading strange error while submitting data

Am using following code to create chat system and store data to txt file. it does what i need but there is a small error while submitting data, when i type text and hit enter AJAX loads data from file chatdata.txt for a second,
Index.html
<?php
session_start();
//Create a session of username and logging in the user to the chat room
if (filter_input(INPUT_POST, 'username')) {
$_SESSION['username'] = filter_input(INPUT_POST, 'username');
}
//Unset session and logging out user from the chat room
if (isset($_GET['logout'])) {
unset($_SESSION['username']);
header('Location:index.php');
}
?>
<html>
<head>
<title>Simple Chat Room</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/style.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div class='header'>
<h1>
SIMPLE CHAT ROOM
<?php // Adding the logout link only for logged in users ?>
<?php if (isset($_SESSION['username'])) { ?>
<a class='logout' href="?logout">Logout</a>
<?php } ?>
</h1>
</div>
<div class='main'>
<?php //Check if the user is logged in or not ?>
<?php if (isset($_SESSION['username'])) { ?>
<div id='result'></div>
<div class='chatcontrols'>
<form method="post" onsubmit="return submitchat();">
<input type='text' name='chat' id='chatbox' autocomplete="off" placeholder="ENTER CHAT HERE" />
<input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
<input type='button' name='clear' class='btn btn-clear' id='clear' value='X' title="Clear Chat" />
</form>
<script>
// Javascript function to submit new chat entered by user
function submitchat() {
if ($('#chat').val() == '' || $('#chatbox').val() == ' ')
return false;
$.ajax({
url: 'chat.php',
data: {chat: $('#chatbox').val(), ajaxsend: true},
method: 'post',
success: function (data) {
$('#result').html(data); // Get the chat records and add it to result div
$('#chatbox').val(''); //Clear chat box after successful submition
document.getElementById('result').scrollTop = document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
}
})
return false;
};
// Function to continously check the some has submitted any new chat
setInterval(function () {
$.ajax({
url: 'chat.php',
data: {ajaxget: true},
method: 'post',
success: function (data) {
$('#result').html(data);
}
})
}, 1000);
// Function to chat history
$(document).ready(function () {
$('#clear').click(function () {
if (!confirm('Are you sure you want to clear chat?'))
return false;
$.ajax({
url: 'chat.php',
data: {username: "<?php echo $_SESSION['username'] ?>", ajaxclear: true},
method: 'post',
success: function (data) {
$('#result').html(data);
}
})
})
})
</script>
<?php } else { ?>
<div class='userscreen'>
<form method="post">
<input type='text' class='input-user' placeholder="ENTER YOUR NAME HERE" name='username' />
<input type='submit' class='btn btn-user' value='START CHAT' />
</form>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Chat.php
<?php
session_start();
$filename=$_SESSION['username'];
$nametxt= "$filename.txt";
$message='created successfully';
if (file_exists($nametxt)) {
$fh = fopen($nametxt, 'a');
} else {
$fh = fopen($nametxt, 'w');
fwrite($fh, $message."\n");
}
fclose($fh);
if(filter_input(INPUT_POST, 'ajaxsend') && filter_input(INPUT_POST, 'ajaxsend')==true){
// Code to save and send chat
$chat = fopen($nametxt, "a");
$data="<b>".$_SESSION['username'].':</b> '.filter_input(INPUT_POST, 'chat')."<br>";
fwrite($chat,$data);
fclose($chat);
$chat = fopen("chatdata.txt", "r");
echo fread($chat,filesize("$nametxt"));
fclose($chat);
} else if(filter_input(INPUT_POST, 'ajaxget') && filter_input(INPUT_POST, 'ajaxget')==true){
// Code to send chat history to the user
$chat = fopen($nametxt, "r");
echo fread($chat,filesize("$nametxt"));
fclose($chat);
} else if(filter_input(INPUT_POST, 'ajaxclear') && filter_input(INPUT_POST, 'ajaxclear')==true){
// Code to clear chat history
$chat = fopen($nametxt, "w");
$data="<b>".$_SESSION['username'].'</b> cleared chat<br>';
fwrite($chat,$data);
fclose($chat);
}
can someone help me sort error, why AJAX loads data from chatdata.txt while submitting data.
If you used index.html instead of index.php, this will not work!
Then after, You might have forgotten to change the "chatdata.txt" on line 22 to $nametxt.
I tried the change and it worked!!

chat app with user typing partly working

This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>
The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds

get and show constant from external webpage and update when change

this script receive time from www.time.is and from #twd ID and show when click on the send btn.
I have two problems:
1-only show first receive time and don't update when click on send again
2- page refresh and lose data
I have Three problem with below code:
<?php include 'simple_html_dom.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled 1</title>
<script src="js/jquery.js"></script>
</head>
<body>
<form action="" method="POST">
<input id="url" name="url" type="text" value="http://www.time.is/">
<input id="address" name="address" type="text" value="#twd">
<input id="send" type="submit" value="get">
</form>
<ul id="times">
</ul>
<script type="text/javascript">
$("#send").click(function(events) {
events.preventDefault();
var url = $("#url").val();
var address = $("#address").val();
var dataString = 'url=' + url + '&address=' + address;
$.ajax({
type: "POST",
url: "read.php",
data: dataString,
success: function() {
var result = "<?php echo getme($url,$address); ?>";
alert(result);
$('#times').append('<li></li>');
}
});
return true;
});
</script>
<?php
function getme($url, $address) {
$html = file_get_html($url);
$code = $html->find($address, 0);
return $code;
}
echo getme($url, $address);
?>
</body>
</html>
any body can help me ..
Thanx all
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function timer(){
$.post( "process.php", function( data ) {
$('#times').append('<li>'+data+'</li>');
});
}
setInterval(function(){timer()},1000);
});
</script>
</head>
<body>
<ul id="times"></ul>
</body>
</html>
And put this in your process.php file:
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.time.is/');
foreach($html->find('#clock0') as $element){
echo $element->plaintext;
}
?>
This is my test result:
11:15:43AM
11:15:46AM
11:15:51AM
11:15:53AM
11:15:53AM
11:16:10AM
11:15:52AM
11:15:42AM
11:16:09AM
11:16:17AM
11:16:12AM
Note:
1- It is advisable that you change intervals from 1000 milliseconds (1 second).
2- Don't forget to use clearInterval() after specific repeat.

Refresh PHP SESSION var after AJAX request

I've index.php and callSession04.php. When index.php does an AJAX request PHP SESSION variables are set on callSession04.php to store the current page and rows per page but on index.php PHP SESSION variables stay as initial state until I refresh index.php
You can see the example here, Need to refresh page before each AJAX request:
http://www.sanchezvalero.com/DWS/pracSESIONES/ej4/sesion04.php
And here is the code:
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
$("#content").html(data);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
$("#content").html(data);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp=<? echo $_SESSION['actp']; ?>&rows=<? echo $_SESSION['rows']; ?>",
success: function(data) {
$("#content").html(data);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
$_SESSION['rows']=$rows;
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
echo "<p align='center'><strong>EMPLEADOS</strong></p>";
echo "<table border='1' cellspacing='0' cellpadding='5'>";
echo "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
echo "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>
<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
echo "</table>";
?>
I need to know how refresh PHP SESSION VARS on index.php withouth press F5.
Finally I solved this, the solution, JSON. Is not necessary to refresh PHP SESSION vars on index.php, only on callSession04.php, simply I've to use AJAX callback to reflect the current server state parsing JSON array on index.php from callSession04.php then you can set new current page and rows per page vars.
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
$rows=10;
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
$rows=<? echo $_SESSION['rows']; ?>;
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
var json = $.parseJSON(data);
$("#content").html(json.html);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
var json = $.parseJSON(data);
$rows=json.rows;
$("#content").html(json.html);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp="+$actp+"&rows="+$rows,
success: function(data) {
var json = $.parseJSON(data);
$actp=json.actp;
$("#content").html(json.html);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['rows']=$rows;
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
$html = "<p align='center'><strong>EMPLEADOS</strong></p>";
$html .= "<table border='1' cellspacing='0' cellpadding='5'>";
$html .= "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
$html .= "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>";
$html .= "<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
$html .= "</table>";
$aPag = array("rows"=>$rows,"actp"=>$actp,"html"=>$html);
echo json_encode($aPag);
?>
The session state is on the server, your code updates it on the server correctly (I assume). What you experience is the representation of the server state (index.php) is not updated on the client (browser) after the Ajax call.
You have multiple options to fix that:
Use the ajax callback to reload the current page (index.php)
Use the ajax callback to update the current page (DOM manipulation) to reflect the server state
This can not be fixed in the php (server side) alone.

jQuery, AJAX & PHP: Arrays on server and client data

My goal is to dynamically display information via PHP that is then editable via AJAX/json. I have this working for a single instance of the server data, but when I get into multiple instances I am getting lost on how to keep the element and div identities distinct via array on the json page as well as in the jQuery output on the main page.
This is the current main page (minus the irrelevant to this question PHP record grabbing). The references in the jQuery are not entirely correct, e.g.
data:$("#form_static_").serialize()
because it is placing the dynamic identifier after the static_ that I don't know how to handle.
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data:$("#form_static_").serialize(),
dataType:"json",
success:function(msg){
$("#formResponse_").removeClass('error');
$("#formResponse_").addClass(msg.status_);
$("#formResponse_").html(msg.message_);
$("#static_name_").html(msg.name_);
$("#static_description_").html(msg.description_);
},
error:function(){
$("#formResponse_").removeClass('success');
$("#formResponse_").addClass('error');
$("#formResponse_").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
</head>
<body>
<div id="tabs-left-2" class="content">
<h1 class="page-title">Static Info</h1>
<?php do { ?>
<div id="static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading"><?php echo $row_rsStatic['name']; ?></div>
<div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>
<div id="static_update_<?php echo $row_rsStatic['id']; ?>" style="display:inherit">
<form id="form_static_<?php echo $row_rsStatic['id']; ?>" name="form_static_<?php echo $row_rsStatic['id']; ?>" method="post" action="">
<div id="formResponse_<?php echo $row_rsStatic['id']; ?>"></div>
<div id="form_static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading">
<input name="id<?php echo $row_rsStatic['id']; ?>" type="hidden" value="<?php echo $row_rsStatic['id']; ?>">
<input name="name<?php echo $row_rsStatic['id']; ?>" type="text" value="<?php echo $row_rsStatic['name']; ?>"></div>
<div id="form_static_description_<?php echo $row_rsStatic['id']; ?>">
<textarea name="description<?php echo $row_rsStatic['id']; ?>"><?php echo $row_rsStatic['description']; ?></textarea>
<script>CKEDITOR.replace('description<?php echo $row_rsStatic['id']; ?>');</script>
</div>
</form>
</div>
<hr>
<?php } while ($row_rsStatic = mysql_fetch_assoc($rsStatic)); ?>
</div>
</body>
</html>
This is the json page, again with the dynamic identifiers left off after the respective "_" as I don't know how to make this happen programmatically:
<?php
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['static_name_'])){
//set the response
$response_array['status_'] = 'error';
$response_array['message_'] = 'Name is blank';
//check the message field
} elseif(empty($_POST['static_description_'])) {
//set the response
$response_array['status_'] = 'error';
$response_array['message_'] = 'Description is blank';
//form validated
} else {
//(update record here)
//set the response
$response_array['status_'] = 'success';
$response_array['message_'] = 'Success!';
$response_array['name_'] = $_POST['static_name_'];
$response_array['description_'] = $_POST['static_description_'];
}
echo json_encode($response_array);
?>
I have been doing PHP forever but am new to the AJAX/JSON/jQuery world, so not sure that the way this is set up is even ideal for dynamically produced/updated data. Any ideas or advice is greatly appreciated... thanks!
EDITS #1:
I changed the files to the following, and know I am still missing something as it does not correctly update:
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
e.stopPropagation();
var form = $(this); // We're going to use this instead of all those IDs
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data: form.serialize(),
dataType:"json",
success:function(msg){
$(".response", form)
.removeClass('error')
.addClass(msg.status)
.html(msg.message);
$(".name", form).html(msg.name);
$(".description", form).html(msg.description);
},
error:function(){
$(".response", form)
.removeClass('success')
.addClass('error')
.html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
</head>
<body>
<div class="small_content_heading name"><?php echo $row_rsSafety['name']; ?></div>
<div class="small_content description"><?php echo $row_rsSafety['description']; ?></div>
<div style="display:inherit">
<form method="post" action="">
<div class="response"></div>
<div class="small_content_heading">
<input name="id" type="hidden" value="<?php echo $row_rsSafety['id']; ?>">
<input name="name" type="text" value="<?php echo $row_rsSafety['name']; ?>">
</div>
<div>
<textarea name="description"><?php echo $row_rsSafety['description']; ?></textarea>
<script>CKEDITOR.replace('description');
function CKupdate(){
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
}
</script>
</div>
<input type="submit" name="submitForm" value="Edit" onClick="CKupdate();">
</form>
</div>
<hr>
</body>
</html>
JSON file:
<?php
//connect to DB
require_once('Connections/job_tool.php');
mysql_select_db($database_job_tool, $job_tool);
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the message field
} elseif(empty($_POST['description'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated
} else {
//set update variables
$update_name = $_POST['name'];
$update_desc = $_POST['description'];
$update_id = $_POST['id'];
//update file on server
$sql = "UPDATE static_fields SET name='$update_name', description='$update_desc' WHERE id='$update_id'";
$update_sql = mysql_query($sql, $job_tool) or die('Could not update data: ' . mysql_error());
mysql_close();
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Update complete!';
$response_array['name'] = $_POST['name'];
$response_array['description'] = $_POST['description'];
}
echo json_encode($response_array);
?>
Rather than using IDs all the time, use jQuery context and classes:
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
e.stopPropagation();
var form = $(this); // We're going to use this instead of all those IDs
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data: form.serialize(),
dataType:"json",
success:function(msg){
$(".response", form)
.removeClass('error')
.addClass(msg.status);
.html(msg.message);
$(".name", form).html(msg.name);
$(".description", form).html(msg.description);
},
error:function(){
$(".response", form)
.removeClass('success')
.addClass('error')
.html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
So, rather than this:
<div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>
You'll use a class instead:
<div class="small_content description"><?php echo $row_rsStatic['description']; ?></div>
The approach:
Use generic classes for your DIVs
Use generic names for your INPUTs
In your PHP $_POST handler, use the hidden ID field to know which record you're working with
In your JSON response, use generic status, message, name, and description keys

Categories