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));
?>
Related
i wanna store html tags value in a variable then send them to database, is there any way for this?
function start(){
$title = $_POST['title'];
$text = $_POST['content'];
$src = $_POST['thumb'];
if(!empty($title) && !empty($text) && isset($_POST['sendpostbtn'])){
try{
include ("../config.php");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `post` (`title`, `content` , `src`) VALUES ('$title','$text','$src')";
$pdo->exec($sql);
?>
<script type="text/javascript">
alert("successes")
</script>
<?php
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
}else{
?>
<script type="text/javascript">
alert("somethings wrong")
</script>
<?php
}
}
?>
and this is my html code in the same file
<div class="sendpostBox">
<div class="lastpostTitle">
<p>new post</p>
</div>
<form action="sendpost.php" method="post">
<label>title</label>
<input type="text" name="title">
<label>src</label>
<input type="text" name="thumb">
<label>content</label>
<textarea name="content"></textarea>
<input type="submit" name="sendpostbtn" value="send">
</form>
</div>
I've created a form and then i want to send these data to database in the same page, i mean i don't want to open another page for this.
thanks
I've created a form and then i want to send these data to database in
the same page, i mean i don't want to open another page for this.
Simply empty the form action.
Example:
<form action="" method="POST">
......
....
..
</form>
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');
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
I am developing a PhoneGap application that gets some information from MySQL Database. I am struggling when I try to open a HTML page that contains two select input that need to be populated on page load, each one with data from two different tables. I don't why, but they are not getting populated. Please, any help will be very welcome.
HTML CODE
<div data-role="content">
<p></p>
<form id="cname" align="left" action="post" data-ajax="false" >
<label for "id">Employee's Name:</label><br/>
<select name="id" id="id"></select><br/>
<label for "job_id">Job's Name:</label><br/>
<select name="job_id" id="job_id"></select><br/>
<input type="hidden" name="latitued" id="latitued" value="">
<input type="hidden" name="longitude" id="longitude" value="" >
<input type="hidden" name="goo_map_api" id="goo_map_api" value="">
<input type="submit" value="Clock-In" id="enviar_in" data-inline="true">
</form>
</div
Jquery Script both SELECTS
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_emp.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.fullName+"</option>";
});
$("#id").html(items);
});
});
</script>
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_job.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.job_name+"</option>";
});
$("#job_id").html(items);
});
});
</script>
PHP file get_emp.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, fullName from employees";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
PHP file get_job.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, job_name from jobs";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
One more time, I appreciate your time taking a look at this code trying to give me a hand.
Thank you.
Code looks okay to me. Have you set the correct header?
header('Content-Type: application/json');
echo json_encode($data);
At first glimpse the code looks all right. What did you have in the console? Is all the json data there? Otherwise try
$.each(data,function(index,item)
{
$('<option>').val(item.id).html(item.job_name).appendTo("#job_id");
});
Updates:
can you please try adding
error_log(print_r($data,1));
before
echo json_encode($data);
in get_emp.php and check the php_error.log to see if the data is populated on the server side when you load the page
I think it has todo with timing between DOM ready and executing the Jquery script.
In this case your script executes before the DOM is ready. If some objects you are refering to, arent ready yet in the DOM, thus JQuery cant find the object, then JQuery simply stops executing.
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>