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);
}
}
}
Related
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.
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
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>");
I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.
HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.