How to insert jqueryUi (Show Effect -> Drop) in a php page - php

I'm trying to write from my database into my page, using one effect. The objective is, when it writes my comment on the page, show it with an effect.
<?php
if(count($_POST) > 0){
echo '<script language="javascript">';
echo '$( "#toggle" ).toggle( "drop" );';
echo '</script>';
$db = new mysqli("localhost", "root", "usbw", "trab_projeto");
$qr = $db->query("INSERT INTO comments(comment) VALUES ('{$_POST['mensagem']}')");
echo "<fieldset id='toogle'>";
echo "<p>";
$row = $db->query("SELECT * FROM comments ORDER BY comment_id DESC LIMIT 1")->fetch_assoc();
echo $row["comment"];
echo "</p>";
echo "</fieldset>";
}
?>
The part of the script doesn't work.
These code is executed when I click on a submit form.
<div class="cadastro">
<form action="" id="form-msg" method="post" enctype="multipart/form-data">
<fieldset>
<p>
<span><b>Escreva aqui o seu comentário:</b></span><br>
<textarea name="mensagem" style="margin: 0px; width: 511px; height: 119px;"></textarea>
</p>
<input type="submit" value="Enviar">
</fieldset>
</form>
</div>

To return a JSON response, you must first place this in your header(). At the top of your script append:
header('Content-type: javascript/json');
Moving on, to prevent your SQL injection I have changed the driver to PDO which you can find documentation on.
header('Content-type: javascript/json');
$driver = new PDO('mysql:host=localhost;dbname=trab_projeto', 'root', 'password');
$state = false;
if(
!isset($_POST['mensagem']) &&
!empty($_POST['mensagem'])
) {
$driver->Prepare('INSERT INTO comments (comment) VALUES (?)');
$state = $driver->execute(array($_POST['mensagem']));
}
if($state)
{
echo json_encode(array('status' => true));
exit;
}
echo json_encode(array('status' => false));
exit;
For future notice, this 'comment' it not attached to any 'thread' scope. If you have multiple posts, you should give each post a unique ID and cross-reference the post ID with the comment so you can load the comments for that specific post.
You can then use jQuery to send requests like so:
$(document).ready(function() {
var form = $('#form-msg');
comment = form.closest('textarea').val();
$.post('the_file_path.php', { mensagem: comment })
.done(function(response) {
if(response.status) {
// todo: success using the effect below
}
});
});
Note the following code above needs a click() attached to your submit button. Consider removing this line of code:
<input type="submit" value="Enviar">
And using:
<button type='button'>Enviar</button>
So you can target it through the form like so:
form.closest('button').click(function() {
// ...
}
You could use an effect when showing the comment to the user-end like so:
var commentToAdd = document.createElement('p');
commentToAdd.innerHTML = comment;
$('#comments').append(commentToAdd);
commentToAdd.show('slow');

Related

On form, how to get multiple checked checkbox value and add to mysql with php without reload and show confirmation message in div?

I'm trying to get multiple checked checkbox value data added to mysql with php without reloading the form page and show confirmation message in div on form page. At the moment, showing on div works but data is not being sent.
I already have done another similar one which I had almost the same code that had the input as text area so I changed that part and it works but the this one is not working. Could anyone give me help here?
form is in vote.php:
<html>
<form action="vote_received.php" method="post" target="" id="vote-submit">
<input type="hidden" name="recieved-date" id="todayDate" />
<input type="hidden" name="user-occup" id="user-occup" value="<?php $_SESSION['occupation']; ?>" />
<input type="checkbox" name="voting[]" value="How might we improve driver facilities such as lunch rooms or break rooms?" id="voting_1">
<label for="voting_1">How might we improve driver facilities such as lunch rooms or break rooms?</label>
<input type="checkbox" name="voting[]" value="How might be increase driver security at night time?" id="voting_2">
<label for="voting_2">How might be increase driver security at night time?</label>
<input type="checkbox" name="voting[]" value="How might we change the on-call communication with management?" id="voting_3">
<label for="voting_3">How might we change the on-call communication with management?</label>
<input type="checkbox" name="voting[]" value="How might we enhance the passenger conflict management system?" id="voting_4">
<label for="voting_4">How might we enhance the passenger conflict management system?</label>
<br><br>
<input type="submit" name="submit" value="Submit" class="btn align-right"></form>
<script>
$("#vote-submit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = $messages.val(),
url = $form.attr('action');
var posting = $.post(url, { submission : message_value});
posting.done(function(data) {
/* Put the results in a div */
$("#vote_success").html('<h2>THANK YOU!</h2><p>Thank you for your voting. Meeting invitations will be send out on December 7th, 2017.');
/* Hide form */
$form.hide();
});
});
</script>
</html>
the vote_received.php is:
<?php
session_start();
if(isset($_POST['vote-submit'])) {
$voteArray=$_POST['voting'];
$conn = mysqli_connect($servername, $username, $password, $database);
if(is_null($voteArray)) {
echo("<p>You didn't select any topic.</p>\n");
} else {
$N = count($voteArray);
for($i=0; $i < $N; $i++) {
$var1 = $voteArray[$i];
$jobTitle = $_SESSION['occupation'];
$sql = "INSERT INTO vote_response (occupation, voting,
created) VALUES('$jobTitle', '$var1', now())";
$success = mysqli_query($conn, $sql);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $var1;
$conn->close();
}
}
}
?>
Thank you very much!
try to change this part of your code
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = [],
url = $form.attr('action');
$.each($messages, function(idx, val){
message_value.push($(val).val());
});
var posting = $.post(url, { submission : message_value});
on further reading of your code, try to change this part of you code also:
if(isset($_POST['submission'])) {
$voteArray=$_POST['submission'];

How to make Textarea and submit button in .php file hide for every row in database?

been working on some database data calling into a .php file.
The php file contains an "Add" button, a "textarea" and an "submit" button.
I did added some J Query script to it to make the "textarea and submit" button to hide until "add" button is clicked, and both "textarea and submit" to hide when "submit" button is clicked making "add" button reappear.
Ever thing is working fine but only glitch is, the script is only working for first row in the table, leaving the rest of rows uneffected.
I think i should use a loop or something.. spent couple of hours but couldn't able to figure it out by myself.
my script goes as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "the_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$().ready = function() {
$('#text').hide();
$('#textsubmit').hide();
$("#addanswer").click(function() {
$('#addanswer').hide();
$('#text').fadeIn('slow').focus();
$('#textsubmit').fadeIn('slow');
});
$('#text').blur(function(){
$('#text').hide();
$('#textsubmit').hide();
$('#addanswer').fadeIn('slow');
});
}();
});//]]>
</script>
</head>
<body>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<button class="addanswer" id="addanswer"><B>Add Answer</B></button>
<form name="answer" method="post" action="output.php">
<textarea type="text" class="text" name="text" required id="text" placeholder="Please type your question here.."></textarea>
<button type="submit" id="textsubmit" class="textsubmit"><B>Submit</B></button>
</form>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</body>
Since you cannot have multiple occurrences of the same ID, you could do something like this.
<?php
foreach( $your_data as $index => $data ){
echo '<button class="addanswer" id="addanswer_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea style="display:none;" type="text" class="text" name="text" required id="text_'.$index.'" placeholder="Please type your question here.."></textarea>';
echo '<button style="display:none;" onClick="addanswer('.$index.');" type="submit" id="textsubmit_'.$index.'" class="textsubmit"><B>Submit</B></button>';
echo '</form>';
}
... Other code stuff.
Now the each row is having a different ID because we have used $index variable. And also we pass the $index to the javascript function as well. So the javascript can do what ever based on the $index value.
You can have your javascript function, something like this.
<script type='text/javascript'>
function addanswer(index){
$('#addanswer_' + index).hide();
$('#text_' + index).fadeIn('slow').focus();
$('#textsubmit_' + index).fadeIn('slow');
}
</script>
Note: I havent checked this code by running it. I think you will get some understanding with this.
Thanks

Constant Updating php Query

i need to update a message box every second or so and i dont really have a clue what to do and i also do most coding differently to what i find online, heres my code
<?php
//first connect to the database
require_once('includes/connect.php');
$sql = "SELECT * FROM `MetalM` WHERE `class` LIKE :msg";
$paragraph = $pdo->prepare($sql);
$paragraph->bindValue(':msg','Message',PDO::PARAM_STR);
$paragraph->execute();
?>
This is the code for my connection
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=DATABASE', 'USER',
'PASSWORD');
}
catch (PDOException $e)
{
echo 'Unable to connect to the database server.';
exit;
}
?>
this is the code for where my messages are being loaded
<div id="mesgBox">
<?php
foreach ($paragraph as $key) {
echo '<div id="messages"><p>'.$key['Name'].': <br>'.$key['Message'].'</p></div>';
}
?>
</div>
<div id="sndmsg">
<h1>Message:</h1>
<form action="insert.php" method="GET">
<input id="meassage" name="meassage" type="text" placeholder="Text Here">
<input id="submit" type="submit" value="Send">
</form>
<br>
</form>
</div>
You will need to do this with Ajax.
You ll need to set Set up a timer that will retrieve every x seconds the new data
for example:
Requirements: jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.post ('/get-update.php', function(data,success)
{
if (success=='success')
if (data.status=='ok')
$('#messages').html(data.Messages);
},'json');
},5000);
</script>
Now, you will have to change your php a little bit in order to make this work.
-- EDIT --
ok, let me refine..
You will need to include jquery lib in your head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Then you will need to have a php file which does exactly what you need to do.... (bring the new messages)
as in:
<?php
// file name: get-update.php
// Just this code here.
require_once('includes/connect.php');
$sql = "SELECT * FROM `MetalM` WHERE `class` LIKE :msg";
$paragraph = $pdo->prepare($sql);
$paragraph->bindValue(':msg','Message',PDO::PARAM_STR);
$paragraph->execute();
$TextBuffer ="";
$StringFormat = "<div id='messages'><p>%s : <br>%s</p></div>";
while ($row = $paragraph->fetch(PDO::FETCH_ASSOC))
$TextBuffer .= sprintf($StringFormat, $row['Name'],$row['Messagge']);
echo json_encode(array("status"=>"ok","Messages"=>$TextBuffer));
?>

Remove HTML tags in textaera (Basic CMS)

I am very new to PHP and started making a light weight CMS. I have stored all the body content in the database and the CMS calls it from the database and displays it in a text area to be edited. However I was wondering is there a way to make it display the text without HTML tags. I have tried the strip_tag function however when I hit save on my cms it saves without the html tags! how will I go about making it display the data from the database without HTML tags but when I save it, it will save with the HTML tags! Sorry if this question is not clear but it is quite difficult to explain. Here is my code so far working fine:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<?php
$sql = "SELECT * FROM content WHERE id = '5'";
$result = mysql_query($sql, $connect);
$num= mysql_numrows($result);mysql_close();
$row = mysql_fetch_row($result);
$pg_content = $row['1'];
if (isset($_POST['saveChanges'])){
$pgcontent = $_POST['edit'];
$sql_query = ("UPDATE content SET cage_content= '$pgcontent' WHERE cage_content= '$pg_content'");
mysql_query($sql_query,$connect);
header('location: admin_cms_staff.php');
$feedback = "Updated successfully";
}
?>
<div id="cms_container"><br>
<h1>Staff Page<img src="images/three_column_grid_line.png" alt="line"></h1>
<form id="form1" name="form1" method="post">
<textarea id="content" name="edit"><?php echo $pg_content; ?></textarea>
<input type="submit" class="submit_edit" value="Save" name="saveChanges" onClick="alertFunction()">
</form>
<p class="logout_btn">Back</p>
<?php if(isset($_POST['saveChanges'])){
echo $feedback;}?>
</div><!--cms_container-->
<script>
function alertFunction()
{
var r=confirm("Do you want to save the changes you made to the page?");
if (r==true)
{
}
else
{
return;
}
}
</script>
</body>
</html>
Change this:
$pgcontent = $_POST['edit'];
to:
$pgcontent = strip_tags($_POST['edit']);
And also change this:
<textarea id="content" name="edit"><?php echo $pg_content; ?></textarea>
to:
<textarea id="content" name="edit"><?php echo strip_tags($pg_content); ?></textarea>

storing the value of GET variable

I have a search bar on the first page and the results are shown on the second page with pagination. The problem is the pagination isn't working with $_GET or $_POST variable.
what I meant is like when the form is submitted the url on second page changes to something like
products.php?search=something and I am able to see the results that show up.
However when I hit the next button of the pagination I get undefined index search error and the url changes to products.php?page=2
so is there any way that I can store the $_GET['search']; value so that I can use it when the page number changes?
<form action="products.php" method="post">
<input type="text" name="search">
<input type="Submit">
</form>
products.php
<?php
/*
* Connect to the database (Replacing the XXXXXX's with the correct details)
*/
try
{
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', '');
}
catch(PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
/*
* Get and/or set the page number we are on
*/
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
/*
* Set a few of the basic options for the class, replacing the URL with your own of course
*/
$options = array(
'results_per_page' => 100,
'url' => 'products.php?page=*VAR*',
'db_handle' => $dbh
);
$q = $_GET['search'];
/*
* Create the pagination object
*/
try
{
$paginate = new pagination($page, "SELECT * FROM products where title LIKE '%$q%' order by id desc", $options);}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$paginate_result = $paginate->resultset->fetchAll();
foreach($paginate_result as $row)
{
echo $row['title'];
}
?>
<?php echo "<li>"; //this is next and prev button for the pagination class if results exceed the limit.
echo $ball->links_html;
echo "</li>"; ?>
Change your code to something like this ...
<form action="products.php" method="get">
<input type="text" name="search">
<input type="Submit">
</form>
... and ...
$options = array(
'results_per_page' => 100,
'url' => 'products.php?search=' . urlencode($_GET['search']) . '&page=*VAR*',
'db_handle' => $dbh
);
The easiest solution would probably be to use a hidden field in your form:
<form action="products.php" method="post">
<input type="text" name="search">
<input type="hidden" name="page" value="<?php echo $_GET['page']; ?>">
<input type="Submit">
</form>
Try Session variables, they let you store it until the browser is closed(or you switch to another website maybe?) and store it across pages.
http://www.tizag.com/phpT/phpsessions.php
The other alternative is cookies, which will let you store for just about as long as you want unless the user deletes their cookies.
http://www.tizag.com/phpT/phpcookies.php

Categories