I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with
Related
I am building a basic commenting system for a website: Comments can be made and users can reply on every comment. I am using ajax for submitting and retrieving/displaying the comments and replies. I have successfully coded the comments part, but need assistance on the replies part.
Every comment stored in the database has a unique id (comment_id) associated with it. And I use that id to associate replies to each respective comment.
The form for the comments, which is in index.php:
<div id="showComments"></div> <!--div where comments are inserted by AJAX-->
<div style="text-align:center;">
<form action="" method="post" id="commentForm">
<textarea name="comment" id="comment" rows="1"></textarea><BR>
<button type="submit" name="new_comment" onClick="submitComment()">Comment</button>
</form>
<div id="message"></div> <!--div where a status (comment submitted successfully or failed) is inserted by AJAX-->
</div>
The JavaScript for submitting the comment and displaying the comments, also in index.php.
<script>
$(document).ready(function() {
showComments();
});
function submitComment(){
var commentText = document.getElementById('comment').value;
var commentString = 'comment=' + commentText;
event.preventDefault();
$.ajax({
url: "insert_com.php",
method: "POST",
data: commentString,
dataType: "JSON",
success: function(response) {
if (!response.error) {
$("#commentForm")[0].reset();
$("#message").html(response.message);
showComments();
} else if (response.error) {
$("#message").html(response.message);
}
}
});
}
function showComments() {
$.ajax({
url: "get_com.php",
method: "POST",
success: function(response) {
$("#showComments").html(response);
}
});
}
</script>
The file insert_com.php, which submits the comment to the database, to where AJAX posts in the submitComment() function:
<?php
if(!empty($_POST["comment"])){
$new_com_date = date('Y-m-d H:i:s');
$insertComment = "INSERT INTO comments (text, date) VALUES ('".$_POST["comment"]."', '".$new_com_date."')";
mysqli_query($connect, $insertComment) or die("database error: ". mysqli_error($connect));
$message = '<label>Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label>Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
And the file get_com.php, which retrieves and displays the comments but also retrieves the replies and contains the form for submitting the replies
<?php
require 'php/connect.php';
$comment = mysqli_query($connect, "SELECT * FROM `comments` ORDER BY `date` DESC");
$string ="";
foreach($comment as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$comment = $item['text'];
$comment_id = $item['id'];
$string .= '<div style="text-align:center;">'
.'<div id="'.$comment_id.'" style="text-align:center;">'
.'<span><b>'.$comment.'</b></span> '
.'<span><b>'.$date.'</b></span> '
.'<span><b>'.$comment_id.'</b></span>'
.'</div>';
$reply = mysqli_query($connect, "SELECT * FROM `replies` WHERE `comment_id`='$comment_id' ORDER BY `date` DESC");
foreach($reply as $com) {
$reply_date = new dateTime($com['date']);
$reply_date = date_format($reply_date, 'M j, Y | H:i:s');
$reply_com = $com['text'];
$com_id = $com['comment_id'];
$string.= '<div>'
.'<span>'.$reply_com.'</span> '
.'<span class="time">'.$reply_date.'</span> '
.'<span><b>'.$com_id.'</b></span>'
.'</div>';
}
$string .=
'<div>'
.'<form action="" method="post" id="replyForm">'
.'<textarea name="new-reply" id="new-reply" rows="1"></textarea>'
.'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
.'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
.'<span><b>'.$comment_id.'</b></span>'
.'</form>'
.'<span id="replymessage"></span>'
.'</div>'
.'</div>'
.'<hr style="width:300px;">';
}
echo $string;
?>
Now, here is where the problem comes in. I want to use AJAX to submit a reply to a particular comment with an id $comment_id. I want to get this id from the hidden input contained in the reply form (The form with id replyForm.
I wrote the following JavaScript to retrieve the id belonging to a particular comment:
<script>
function submitReply(){
var replyText = document.getElementById('new-reply').value; console.log(replyText);
var commId = document.getElementById('com_id').value; console.log(commId);
event.preventDefault();
...
</script>
As you can see, I log the form text (the reply) and the comment id to the console to see whether I am capturing the correct data, but it always returns the id of the last comment submitted. (i.e the reply form works for the last comment. The JavaScript logs the correct text and comment id for a reply on the last comment, but for all other replies it returns the text of the reply on the last comment and the id of the last comment.
I know it's quite a lot of code, so if anyone more experience could assist me it would certainly be appreciated.
You have more than one element with id="com_id". id should be unique. What you can do is when you are generating the DOM in get_com.php, instead of
'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
You can call submitReply() with the right ID, like so:
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply('.$comment_id.')">Reply</button> '
Then, the comment ID would be the argument of your submitReply method and you wouldn't need to read it from the input field.
<script>
function submitReply(commId){
var replyText = document.getElementById('new-reply').value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
Your <textarea> has the same issue as well.
I suggest to assign a unique ID to your <textarea> as well, something like "reply-'.$comment_id.'". Then, when submitReply(comment_id) gets called, you know which comment ID is the call for, so you can construct the unique ID for the exact same textarea, and get the value of the desired element.
<script>
function submitReply(commId){
var replyText = document.getElementById('reply-' + commId).value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
I have this code to display a user's name:
<div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div>
I'd like to change what's displayed in <span id="output"></span> when a user changes their profile.
This is what I use to change their profile data in the database (shortened to only include what's needed):
<form action="" method="POST">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<button type="submit" name="submit">Submit</button>
</form>
if (isset($_POST['submit'])) {
$username = $_SESSION['username'];
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($connect, $query) or die(mysqli_error());
$profile = mysqli_fetch_assoc($result);
$update = "UPDATE users SET firstname = '$firstname' WHERE username = '$username'";
$result2 = mysqli_query($connect, $update);
if (mysqli_query($connect, $update)) {
$_SESSION['firstname'] = $firstname;
echo 'Profile updated successfully';
}
}
The thing is, I don't know how to change the "output" to the new $_SESSION['firstname'] without refreshing the page.
I would assume that I'd need to use JQuery's ajax function, but I'm not sure how to specifically use this function to get it done.
A lot of things are wrong with the code. Besides that point here is a simple ajax request.
$('.submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'yourscript.php',
data: {firstname: $('#firstname').val()},
success: function(data){
$('#firstname').html(data);
}
});
})
And for PHP:
# 'yourscript.php',
if(isset($firstname = $_POST['firstname'])){
// do your stuff.
echo 'your new data you want to display';
} else {
echo 'something went wrong';
}
I have this chat room on my website, where the user types their message into a textbox and when they press enter (or the send button), jQuery takes the data from the textbox, disables the textbox, sends the data to the file send.php where it is then processed and put into the database, and then it should clear and undisable the textbox once it successfully runs through the PHP script. What is happening is the data is being submitted and it runs through the script (sends the data to the database successfully) but the jQuery is not clearing and undisabling the textbox.
Can someone explain to me what is wrong?
jQuery:
$('#formSend').on('submit', function (e) {
e.preventDefault();
var textArea = document.getElementById('styled');
if( textArea.value != "" ) {
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
dataType: "json",
success: function (formData) { //put data in parentheses when coming back
alert("Success");
$(".expand").val('');
$('.expand').prop("disabled", false);
if( formData["banned"] == 1 ) {
var rel = confirm("You have been banned.");
if (rel) {
location.reload();
}
else {
location.reload();
}
}
}
});
}
else {
alert("Your message must be longer than 1 (one) character.");
$('#styled').focus();
}
});
send.php:
<?php
include("../config.php");
session_start();
$msg = strip_tags( $_POST['msg'], '<b></b>' );
if( $msg == "" ) {
exit("There is no message.");
}
$username = $_SESSION['USER'];
$date = new DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$stmt = $db->prepare("SELECT id, username FROM users WHERE username = :username");
$stmt->execute(array(":username" => $username));
$row = $stmt->fetch();
$userID = $row['id'];
$checkBanned = $db->prepare('SELECT banned FROM users WHERE username = :username');
$checkBanned->execute(array(
':username' => $username
));
$banned = $checkBanned->fetch();
if( $banned['banned'] == "yes" ) {
$return = array('banned' => 1);
echo json_encode($return);
exit;
}
try {
$stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)');
$stmt->execute(array(
':userID' => $userID,
':msg' => $msg,
':date' => $formattedDate
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Here is the form too, if needed.
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
I think the problem is you have not sent any responce if user is not banned and message is stored successfully.
If "success" is not being alerted then that is the problem.
Try this,
try { $stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)'); $stmt->execute(array( ':userID' => $userID, ':msg' => $msg, ':date' => $formattedDate ));
$output = "success";
} catch(PDOException $e) { $output = $e->getMessage(); }
finally{
echo json_encode($output);
}
I see you are refreshing the page afterwards, that could make the form to autocomplete to the previous value, try this:
<form autocomplete="off" action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
If you dont want to reload the page (which should actually happen, if you dont prevent the submit event from beeing triggered in the ajax callback by event.preventDefault()) you have to reset the form by doing something like $('#formSend').reset();
Furthermore, there is no disabled='false', you need to remove the attribute: $('.expand').removeAttr('disabled');.
By the way, it is good habit to save selector you need more than one time ;)
Have you tried something like:
$('.expand').removeAttr("disabled");
Is it possible to run a php file/function without entering the page?
I mean it is really disturbing if you create for example a chat app and when you submit your message the whole page get reloaded.
I've tried AJAX but didn't worked. Is it impossible to post the text of the chat_area to the PHP file?
<form action="..." method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<?php
session_start();
include_once( "database.php" );
if( $_POST["chat_area"] ){
$name = $_SESSION["firstname"]
$time = "[" . date( "H:i", time() + 3600 ) . "]";
$message = $_POST["chat_area"]
mysql_query( "INSERT INTO chat( name, time, message ) VALUES ('$name', '$time', '$message' )" );
}
?>
It's default behaviour of the form. For chat-like app, you should use ajax. Not only for posting the form data, but also for receiving messages from backend app. Otherwise, you'll have to reload a page to check whether or not you got some new messages.
With jQuery you could use event.preventDefault() to stop the default action of the form to be triggered, and then post the data to PHP.
You should split your app to 2 files. Main page, and file, where all the data is sent to (and received from).
Your front end:
<?php
session_start();
// rest of the PHP, if any...
?>
<form method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#chat_submit').on('click', function(e){
e.preventDefault();
$.ajax({
type : "POST",
url : 'your_php_file.php',
dataType : 'text',
data :{
message : $('#chat_area').val()
},
success : function(data){
if(data == 'success'){
// E.g.: append the message to chat area after it is successfully stored in DB.
}
},
complete : function(status){
// call on complete
},
error : function(response){
// call when error
}
});
});
});
</script>
PHP (your_php_file.php):
<?php
session_start();
include_once("database.php");
if( isset($_POST["message"]) ){
$name = $_SESSION["firstname"];
$time = "[" . date( "H:i", time() + 3600 ) . "]";
// a little of safety:
$unsafe_message = trim($_POST["message"]);
$safe_message = mysql_real_escape_string($unsafe_message);
mysql_query
( "INSERT INTO chat( name, time, message )
VALUES
('$name', '$time', '$safe_message' )" ) or die('error');
echo 'success';
}else{
echo 'error';
}
?>
I've got a problem with a html form. Php seems to remember my POST value after refreshing my page. It has to do with a login form that I uses.
I'm using cookies to let php communicate with javascript, telling javascript if the user is logged in or not.
Php code:
<?php
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = MD5($_POST['password']);
echo '<script>console.log("' . $username . '", "username"); </script>';
echo '<script>console.log("' . $password . '" , "password"); </script>';
/* against sql injections */
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = "SELECT user_id FROM User WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row[user_id]){
$cookie_name = "login";
$cookie_value = "1";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
} else{
echo '<script> alert("Incorrect username and password combination");</script>';
}
}
?>
The form:
<form method="POST" id="loginForm">
<b>Login</b>
<table style="margin-top: 10px">
<tr><td>Username: </td><td><input type="text" name="username" placeholder="username" required="required"></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" placeholder="password" required="required"></td></tr>
<tr><td><input type="submit" name="login" value="Login" style="margin-top: 5px"></td></tr>
</table>
</form>
Because I love javascript, I'm using a ajax call to communicate with php and the server database.
Javascript code:
function openPage(page) {
var content;
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
document.getElementById('contentMiddle').innerHTML = data;
}
});
}
}
The problem is whenever I try to refresh the page, my php code will always run and $_POST['username'] and $_POST['password'] will always have the POST value from before refreshing the page.
I always make sure I remove the cookie before refreshing the page.
Any idea?
You've most likely already submitted the page and by hitting refresh the browser is attempting to send the POST data along with the refresh.
Since you're using Ajax to process your form you can/should remove type="submit" from the login button since there's no need for it. Instead you can have Login.
Then update your Ajax to run when the button is clicked. You can also use jQuery to get your elements by ID, for example:
$("#btn_login").on("click", function() {
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
//document.getElementById('contentMiddle').innerHTML = data;
$("#contentMiddle").html(data);
}
});
});
To address the comment by #charlietfl, handling an Enter press to submit the form you'd use something like this.
document.onkeydown = function(){
if(window.event.keyCode=='13'){
$("#loginForm").submit();
}
}