I have an issue displaying messages from my database. My site has a simple chat room which was working perfectly when reading/writing to a textfile. I am now trying to link it to a database with a table called messages. Whilst I am writing to the table OK, messages are not being displayed on the screen.
By using POSTMAN, I know that I am successfully talking to the backend because when I run a request - {"state":1,"text":["Welcome all users!"]} is returned, which is the last message I had typed, and the json echo ($log) is working.
Apart from an updateChat() function (posted below) I have a function titled getState() which gets the current state of the chat (number of lines, whether new lines added).
Since my SQL queries seem to be working fine, is there an issue with my updateChat() or ()getState function?
Admittedly, I have never built a chatroom before and I am a bit stuck on where to go next.
Thanks for any help or advice!
****chat.js****
//Updates the chat
function updateChat() {
if (!instanse) {
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function (data) {
if (data.text) {
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($( data.text[i] + "</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
}
});
} else {
setTimeout(updateChat, 1500);
}
}
process.php
case('getState'):
$lines = "SELECT messageBody, timeSent, nickname FROM message ORDER BY timeSent";
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
$lines = "SELECT messageBody, timeSent, nickname FROM message ORDER BY timeSent";
$result = mysqli_query($conn, $lines);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$message = $row['messageBody'];
$time = $row['timeSent'];
$nickname = $row['nickname'];
}
}
$count = count($lines);
if ($state == $count) {
$log['state'] = $state;
$log['text'] = false;
} else {
$text = array();
$log['state'] = $state + count($lines) - $state;
$text[] = $message = str_replace("\n", "", $message);
}
$log['text'] = $message;
break;
Try catching errors with ajax, if there are, show us.
regardless,
$('#chat-area').append($( data.text[i] + "</p>"));
this will not work. try this:
$('#chat-area').append("<p>" + data.text[i] + "</p>");
Related
I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend
I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.
I am running a simple chat application and it's powered by a process.php file, but the chat is on chat.php.
Basically people can search for a "Topic", and it'll take them to domain.tld/chat.php?topic=topicname (topicname being whatever they searched for)
I need my process.php file to echo
<?php echo $_GET['topic']; ?>.txt
instead of chat.txt, so that each topic has a unique text file (so that all chats aren't linked)
This is my process.php file:
<?php
$function = $_POST['function'];
$log = array();
switch($function) {
case('getState'):
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = htmlentities(strip_tags($_POST['nickname']));
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
$message = preg_replace('/#(\w+)/', ' #$1', $message);
fwrite(fopen('logs/chat.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n");
}
break;
}
echo json_encode($log);
?>
This is my chat.js file
/*
Created by: Kenrick Beckett
Name: Chat Engine
*/
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
In theory this should create a unique topicname.txt file in /logs/ whenever somebody starts chatting in a topic that's nonexistent. I'm just having trouble adding the topicname in place of chat.txt in process.php. So far I know that it does create a chat.txt file by itself, so it should create a unique .txt file once I echo it correctly.
Also, I'm aware that a database is a better option when compared to storing messages in unique .txt files, but this is how I want to do it.
Here's an example of how I was trying to add it to my process.php a snippet from process.php)
case('getState'):
if(file_exists('logs/<?php echo $_GET['topic']; ?>.txt')){
$lines = file('logs/<?php echo $_GET['topic']; ?>.txt');
}
^ That probably isn't even the right format, as I'm new to PHP and make tons of mistakes, and it probably won't know what the GET is because it's not a part of chat.php ... it's a separate file.
Try with -
'logs/' . $filename . '.txt'
where ever you want.
Update
if (!empty($_GET['topic'])) {
$filename = $_GET['topic'];
} else {
$filename = 'something else';
}
if(file_exists('logs/' . $filename . '.txt')){ $lines = file('logs/' . $filename . '.txt') ....
It is already in php. So no need to add <?php ?> and echo. Just simply concatenate them.
you are already in php tag.. no need to add extra php tags
case('getState'):
if(file_exists("logs/".$_GET['topic'].".txt")){
$lines = file("logs/".$_GET['topic'].".txt");
}
or Try this
case('getState'):
if(isset($_GET['topic']){
$filename = "logs/".$_GET['topic'].".txt";
if(file_exists($filename)){
$lines = file($filename);
}
}
}