automatically load dynamic content with ajax and php - javascript

I have a PHP chat application that automatically get messages from database and displays it, currently everything works fine but page must be manually reloaded to display new messages .. How do I implement JQuery ajax to get the messages or silently refresh the specific messages list div without refreshing the whole page? Here is my code (not the full code on the page but the main PHP part I want to use ajax on)
Some answers I read online specified that the PHP code must be on a separate file but Some of the functions and variables in the code below depends on the main file holding this code therefore making it useless if put in a separate file.
<?php
// Attempt select query execution
global $db;
$id = $_GET["id"];
$sql = "SELECT * FROM msg WHERE id='$id' ";
if ($result = $db->query($sql)) {
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo '<div class="chat-messages-item ' . chattype($row['sender']) . '">';
echo '<div class="chat-avatar chat-avatar-lg circle"><img src="' . senderpic($row['sender'], 'thumbnail', '100', '100') . '" alt=""></div>';
echo '<div class="chat-messages-content">';
echo '<div class="chat-messages-bubble ' . $msg_visibility . '">';
echo '<p>' . $row['message'] . '</p>';
echo '</div>';
echo '<ul class="chat-messages-info">';
echo '<li>';
echo '<div class="chat-time chat-seen"><span>' . $row["time"] . '</span>';
echo '</li>';
echo '</ul>';
echo '</div>';
echo '</div>';
}
unset($result);
} else {
echo "<p class='lead'><em>No Chat</em></p>";
}
} else {
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
Thanks
[EDIT]
What i've tried :
1. Moving the code above into a separate PHP file and using jquery to to get the page with the following js code but nothing appears and no errors displayed. if i open the page in browser it displays the list of all messages
function update() {
$.get("aj/messages.php", function(data) {
$("#allmessages").html(data);
window.setTimeout(update, 10000);
});
}
here is the page structure
- Message.php (the main message page that displays other chat information like contacts, messages list, messages, send message input etc)
aj/msg.php (a php page that gets all the messages from database and wraps it in style/css/html which is also the php code above and expected to be inside a div with the id="allmessages" located inside Message.php)

As you mentioned, it is a good practice to separate your PHP Code and your HTML/JavaScript Code. Yes, this may mean you have to write more PHP Code, yet if PHP Scripts must use the same code snippet, this is where PHP include and include_once can be used so that you can store specific functions in one script and them import them to other scripts. Please see:
https://www.php.net/manual/en/function.include.php
Currently, there is not enough of an example to be able to properly answer your question. I would suggest that you either create a more functional PHP Script that can accept new Chat input or another that can show the current chat transcript from the Database.
In this use case, each member of the chat must send new data to the database and then periodically get/refresh their view of the transcript. You can send new data to the database at any time and then based on a specific refresh rate, look for differences in the transcript. So your JavaScript will have a few function. Something like
startChat()
sendMessage()
getMessages()
endChat()
These will send data to the PHP Script and the PHP Script may give a response. This can all be done with AJAX. AJAX is the use of HTTP GET or POST along with JavaScript. This is basically how a Client Side Script language like JavaScript can talk to a Server Side Scripting language like PHP. PHP is processed when the HTTP request is handled by the Web Server and once the data is sent to the browser, PHP can no longer interact with it, this is why it's a pre-processor. JavaScript can only run in the browser and is processed after all the data from the server is received by the browser.
So if you have some HTML like:
<div class="chat-window">
<div class="transcript">
</div>
<div class="user-input">
<input type="text" /> <button>Send</button>
</div>
</div>
You can use JavaScript to perform tasks when the User types in text and clicks the button. One of those tasks can be to collect the text entered by the User and send it to the PHP Script to be added to the Database. Another task can be to update the field if there are any new messages in the Database since the last time the script checked.
Using jQuery Framework for JavaScript, it might be something like:
function sendMessage(user, txt){
$.post("chat_input.php", { u: user, msg: txt });
}
This creates a HTTP POST call to a PHP Script with a payload of info, such as the User and some Text. You'll need to collect this information from the HTML based on a specific Event.
$(".user-input > button").click(function(){
sendMessage("jsmith", $(this).parent().find("input").val());
});
This bit of jQuery binds a anonymous function as a callback to the click event. When the User clicks the button, it runs that code in the function.
The PHP Code might be something like:
<?php
$user = $_POST['u'];
$txt = $_POST['msg'];
include_once 'db_conn.php';
$stmt = $mysqli->prepare("INSERT INTO 'chat' VALUES (?, ?)");
$stmt->bind_param("ss", $user, $txt);
$stmt->execute();
$stmt->close();
?>
As you can see, this is very rudimentary and will not answer your overall question. You must do a lot of research and I would advise you find example PHP/jQuery Chat example that you can learn from or begin taking some JavaScript/jQuery Tutorials.
See More:
https://api.jquery.com/jQuery.post/
https://api.jquery.com/click/
https://api.jquery.com/category/selectors/
Update
If your PHP Code is setup to collect some data and "send" it back to an AJAX script, then you would prepare it like any other PHP Page, and output the data to the page in some fashion.
<?php
$results = new array();
/* Assuming connection to DB */
/* Assuming SQL Query and result set is now in $results */
header('Content-Type: application/json');
echo json_encode($results);
?>
When you navigate to this page, you will see the collected data in JSON format. Something like:
[
{
"sender": "jsmith",
"message": "Hello World!",
"time": "12/27/2019 10:28:01"
},
{
"sender": "ssmith",
"message": "shut up john",
"time": "12/27/2019 10:28:12"
}
]
When AJAX sends a request to this script, it will get the data back and can then iterate each item in the array, create HTML for it as needed. You can use HTML or Text or XML too, I just use JSON when possible.
In jQuery, this function might look like:
function getMessages(){
var lastMessage = $(".chat-messages-item:last .chat-time").text().trim();
$.get("chatmessages.php", function(data){
$.each(data, function(i, msg){
if(lastMessage < msg.time){
var newMsg = $("<div>", {
class: "chat-messages-item " + chattype(msg.sender),
}).insertAfter($(".chat-messages-item:last"));
var av = $("<div>", {
class: "chat-avatar chat-avatar-lg circle"
}).appendTo(newMsg);
$("<img>", {
src: senderpic(msg.sender, 100, 100),
class: "thumbnail"
}).appendTo(av);
$("<div>", {
class: "chat-messages-content"
}).html("<p>" + msg.message + "</p>").appendTo(newMsg);
}
});
});
}
setTimeout(getMessages, 10000);
This is just an example based on your code.

Related

how to display form content after php processing

Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.

Cannot use echo after connection to database

I'm using ajax to send a request to php with some text.
$.get("process.php", { finalQuery : finalQuery }, function(data) {
alert("Data Loaded: " + data);
});
I know this works because in php I can put
$val = $_GET['finalQuery']; echo $val;
And it outputs the correct data.
However, if I put
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
pg_close($db);
It stops echoing the results back to javascript. If I use a different port or name, and it doesn't connect, it then goes back to sending the data to javascript and outputting the correct data.
So basically, when I connect to the database, I cannot communicate my results back with echo. What am I doing wrong?
EDIT(update):
Here's the complete php code
<?php
$val = $_GET['finalQuery'];
echo $val;
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
$result = pg_query($db, 'SELECT gid FROM "Perfect"');
while ($row = pg_fetch_row($result)) {
echo "gid: $row[0]";
echo "<br />\n";
}
pg_close($db);
?>
However, the problem still occurs as long as I use pg_connect. All the other lines can be removed and the problem persists. As long as I remove the pg_connect, the problem disappears and I can send the information back through echo
NEW EDIT(debugging) :
The connection to the database and the php code seems ok. After loading the php page with
error_reporting(-1);
ini_set('display_errors', 'On');
no errors are logged on the page, and the connection to the database is returning all the data properly on every page load.
The problem arises when I'm trying to connect to the php through javascript.
The page loads the data properly sometimes, but it's random, and most of the time nothing happens (not even php logged errors). If you there's no way the javascript-php connection isn't the problem then I'll keep debugging the code.
Here's the steps I'd take for debug:
Begin by ensuring the DB is running and that you can send it a query
successfully via console window DB GUI Tool (Navicat is my gui of
choice for DB's)
Load the PHP page directly. Check for output of
expected code or fatal PHP Errors
Check the browser console for errors. Since it appears to be a PHP
only page, this should be entirely clear of problems.
Check PHP logs
Check Postgres logs
More than likely, something between Postgres and PHP is the problem. Post any errors back on your question if you're still stuck after finding a clue.

Insert into MySQL database when user clicks on a Link

I am creating a website that has users log in and select a pdf document that they want to download. When they open up the document to view and possibly download, I want data to be logged into a database at the same time.
The code to send the data to the database works (Except for: Undefined index: learningMaterial). But when I want to have the pdf document open and at the same time log the user and other data, all that happens is the document opens up.
Any advice would be appreciated, even for overall better methods of going about what I'm trying to achieve here. Still inexperienced with PHP.
See code below.
HTML
<form name="myform" method='post' action="../includes/writeStats.php">
<input type='hidden' name='learningMaterial' id='learningMaterial' value='learningMaterial'>
<a href='../documents/test.pdf' id='mylink' class='courses' name='Driver Training'> Driver Training </a>
</form>
JS - In header
<script type="text/javascript">
function submitform(){
document.myform.submit(); }
var form = document.getElementById("myform");
document.getElementById("mylink").addEventListener("click", function () {
submitform();
});
</script>
PHP
<?php
$con=mysqli_connect("localhost","root","password","qmptest");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get latest log nr
$result = mysqli_query($con,"SELECT * FROM logbook ORDER BY log DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$log = $row['log'] + 1;
//If statement to check if log is 0(first entry) to go here
}
$date = date("Y/m/d");
session_start(); // Start a new session
$person = $_SESSION['currentUser'];
//Not sure if this is correct along with my HTML input
$material = mysqli_real_escape_string($con, $_POST['learningMaterial']);
//Insert into database
$sql="INSERT INTO logbook (log, date, person, learningMaterial)
VALUES ('$log', '$date', '$person', '$material')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Your way, clicking the link will override the form being submitted. This leads to the file opening and the form never going through.
Instead, you could try either opening the file in a new window by adding target="_blank" to the tag, or send the files URL through to the PHP, executing the database code then adding to the end:
header("Location: http://yourdomain.com/yourfile.pdf");
Your file is just a normal file being returned by your web server:
<a href='../documents/test.pdf' ...
So while you may be able to suggest to users or browsers that they should invoke some code before downloading this file, you can't actually require it. Any user can just request the file directly. And since PDF files don't execute PHP code (thankfully), your server-side PHP code has no way of knowing that the file has been requested.
What you can do is obscure the file itself behind a PHP request. You can create something like a download.php page which accepts the name of a file (test.pdf) and returns that file.
Be very careful when doing this. Don't just allow users to request any file and blindly return whatever they request. A user can request something like "../../../../../../../../../../etc/passwd" and if your code just builds a path and returns the file then you've just given users a sensitive file. It's best practice to keep a finite known list of identified files (perhaps in a database table) and let users request by the identifier rather than by the file path itself. That way the actual path is only ever known server-side in data that you control.
The main point here, however, is that by using such a page you inject some PHP code in between the user and the file. In order to get the file, the user needs to make a request to a PHP page. On that page you can record the act of the user having requested the file. (As well as perform authorization checks to validate that the user is allowed to view the file, etc.)
Never assume client-side code is going to do what you expect it to do. If you want to ensure something happens for anything approaching security or auditing purposes, it needs to happen in server-side code.

How do I auto-refresh my php chat-script?

I am having trouble getting my php chat script to auto refresh when mysql data is changed. I have done a good bit of research and it seems a lot of other people's solutions are more complicated then what I need (I'm going for something very basic).
I do not know any javascript so detailed comments would be appreciated if js is involved.
Here is the php script that I have created. It is functioning (at least for me).
include 'connect2.php';
echo "
Enter a Message:
<form method=post action='' name=chat>
<input type=text name=message>
<input type=submit name=chat value=Submit>
</form>
";
if (isset($_POST['chat'])) {
$message = $_POST['message'];
mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
}
$sql = "select * from chat order by id desc limit 15";
$result = mysql_query($sql) or die ("An error has occured with in the database.");
while ($data = mysql_fetch_assoc($result)) {
$db_message = $data['message'];
$db_user = $data['user'];
echo "$db_user : $db_message <br>";
}
?>
Any help would be appreciated, thanks! :)
You can use setInterval and jQuery library ajax functions to check for it.
For example, it's very simple to do with jQuery:
$(document).ready(function() {
// check once in five seconds
setInterval(function() {
$.get('/script.php', {do: 'new_messages'}, function(response) {
if(response == 1) {
window.location.reload();
}
});
}, 5000);
});
And somewhere on server:
if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
// some your code that detects if there's any new messages, and sets
// $there_are_new_messages to true, if there's any
...
if($there_are_new_messages) {
echo 1;
exit; // avoid further output
}
}
Please remember, that for this to work you need to ensure that there's no output before ajax block, as you can get into unexpected results.
Also consider that using output is not a good practice at all to show your script everything is ok. Better way is to set HTTP header with corresponding response code.
The best way to do this in your case would probably be using Ajax (and jQuery) and refreshing every X seconds.
Ready Handler- http://api.jquery.com/ready/
Javascript Timer- http://www.w3schools.com/js/js_timing.asp
Ajax Request- http://api.jquery.com/jQuery.post/
PHP json_encode- http://php.net/manual/en/function.json-encode.php
$( document ).ready(function() { //set up refresh timer on page load
var refreshTimer = setInterval(function(){refreshMessages()},5000); //creates timer to request every 5 seconds
});
function refreshMessages(){
$.post( "getMessages.php", function( data ) { //fire ajax post request
alert("Got messages: " + data); // this just alerts the data when the request is done, you'll probably want to format/print
});
}
On the getMessages.php side of things, you'll want to pull your messages from the database how you normally would. In this case, json encoding your php messages array would be an easy way for you to iterate the returned object.
<?php
$messages = // get messages array from database
echo json_encode($messages);
?>

Connecting to a MySQL database using PhoneGap, AJAX, and JQuery Mobile

I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:
On our html file, we have a
<script type="text/javascript" src="Connect.js"></script>
^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?
Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {
// cache this page for later use (inside the AJAX function)
var $this = $(this);
// make an AJAX call to your PHP script
$.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {
// create a variable to hold the parsed output from the server
var output = [];
// if the PHP script returned a success
if (response.status == 'success') {
// iterate through the response rows
for (var key in response.items) {
// add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
// if the PHP script returned an error
} else {
// output an error message
output.push('<li>No Data Found</li>');
}
// append the output to the `data-role="content"` div on this page as a
// listview and trigger the `create` event on its parent to style the
// listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
Yet nothing is showing here. What do we do from here?
First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)

Categories