When I click a button an animation runs but the ajax is skipped. This is only a problem on the smartphone screen and not on my computer.
Jquery:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#thisid').hide();
$("#button-create").on('touchstart',(function(event) {
var name = $("#create").val();
var name2 = $("#create2").val();
$("#stage").load('result.php', {name:name, name2:name2} );
});
});
</script>
Button:
<button id="button-create" class="btn1">Create</button>
Html
<div class="col-xs-12 col-lg-6 col" style="text-align:center;">
</div>
<div class="col-xs-12 col-lg-6 col" style="margin-top:20px;text- align:center;">
<input type="input" style="height:24px; margin-right:15px;" id="create" value="Heading">
<button id="button-create" class="btn1">Create</button>
</div>
</div>
</div>
<input type="input" style="float:right; display:none;" id="create2" value="<?php echo $_GET['user']?>">
<div id="stage">
</div>
<input type="input" id="headv" size="40" style="display:none;">
<div id="stage100">
</div>
Result.php
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
$name1_preg = preg_replace('/\s+/', '-', $name);
$name2 = $_RsEQUEST['name2'];
$content = 'Click to edit me, press the save button to save';
session_start();
try {
$pdo = new PDO('mysql:host=localhost;dbname=cms', 'root', 'root');
} catch (PDOException $e) {
}
$query123 = $pdo->
prepare("INSERT INTO post (head, user, content) VALUES (?, ?, ?)");
$query123->
bindValue(1, $name1_preg);
$query123->
bindValue(2, $name2);
$query123->
bindValue(3, $content);
$query123->
execute();
}
?>
Related
I made a login floating form. Whenever I try to login using the correct username and password it takes me to the login form but this time in a simple design and to another page. When I try to login from there nothing happens. Can anyone help me with this?
//logintest.php
<div class="popUpLogin">
<div class="blackBox activate"></div>
<div class="wrapper activate">
<div class="title">
Login Form
<button onclick=" enableActivate() ">×</button>
</div>
<form action="includes/login.inc.php" method="post">
<div class="field">
<input type="text" name="name" required>
<label>Email Address</label>
</div>
<div class="field">
<input type="password" name="pwd" required>
<label>Password</label>
</div>
<div class="content">
<div class="checkbox">
<input type="checkbox" id="remember-me">
<label for="remember-me">Remember me</label>
</div>
<div class="pass-link">
Forgot password?
</div>
</div>
<div class="field">
<input type="submit" value="Login">
</div>
<div class="signup-link">
Not a member? Signup now
</div>
</form>
</div>
<?php
if(isset($_GET["error"])){
if($_GET["error"] == "emptyinput"){
echo "<p>Fill in all feilds!</p>";
} else if($_GET["error"] == "wronglogin") {
echo "<p>Incorrent Login Information</p>";
}
}
?>
</div>
//login.inc.php
<?php
if(isset($_POST["submit"])){
$username = $_POST["uid"];
$pwd = $_POST["pwd"];
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if(emptyInputLogin($username, $pwd) !== false){
header("location: ../logintest.php?error=emptyinput");
exit();
}
loginuser($conn, $username, $pwd);
} else {
header("location: ../logintest.php");
exit();
}
//functions.inc.php
function loginuser($conn, $username, $pwd) {
$uidExists = uidExists($conn, $username, $username);
if($uidExists === false){
header("location: ../logintest.php?error=wronglogin");
exit();
}
$pwdHashed = $uidExists["usersPwd"];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false){
header("location: ../logintest.php?error=wronglogin");
exit();
} else if ($checkPwd === true){
session_start();
$_SESSION["userid"] = $uidExists["usersID"];
$_SESSION["useruid"] = $uidExists["usersUid"];
header("location: ../index.php");
exit();
}
}
In my header.php:
<div class="nav">
<?php
if(isset($_SESSION["useruid"])){
echo "<a href='index.php' class='login' style='color: rgba(47, 128, 237,
1);'>Profile</a>";
} else {
echo "<button onclick='disableActivate()' class='login' style='color: rgba(47,
128, 237, 1);'>Login</button>";
echo "<button onclick='document.location='signup.php' ' class='navSignup'> Get
your free card!</button>";
}
?>
</div>
<?php
include 'logintest.php';
?>
<script>
function disableActivate() {
document.querySelectorAll(".wrapper")[0].classList.remove("activate");
document.querySelectorAll(".blackBox")[0].classList.remove("activate");
}
function enableActivate() {
document.querySelectorAll(".wrapper")[0].classList.add("activate");
document.querySelectorAll(".blackBox")[0].classList.add("activate");
}
</script>
Normally for this event to happen, is after the form has been submitted.
What I see in the code provided could be that you forgot to assign a name for your button. What you need to do is:
HTML:
<input type="submit" name="login" value="Login">
login.inc.php:
if (isset($_POST['login'])){
#login
}else{
#deny access
}
In compiling this code, the browser runs the code and searches for a button called login, and then takes action
Ok, this is my first time logged in, but have a question which I can`t find. Maybe I used the wrong search terms or it is my broken English.
But hopefully, somebody can point me in the right direction.
My situation. I have a list of users. When I click on one of them a second screen opens using javascript/AJAX. Some CSS styling does the split screen thing.
In the second screen, I show a form with some info or not. So far so good.
What I want is that when you change some info and you press the submit/save button, data gets saved in the database without a page refresh. But I can't get it right. When I press the button the ajax split-screen disappears. But the page that I linked on the jquery does nothing.
Some code is in Dutch so ask if you need translation.
My code is as follows:
Page users.php
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
</script>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
Page ajaxBeheer.php
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" method="POST">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="firstname" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<style type="javascript">
function save(){
var query = $('#formId').serialize();
var url = 'updateUser.php';
$.post(url, query, function (response) {
alert (response);
});
}
</style>
page updateUser.php
<?php
$table = 'userinfo';
$data = array('user_firstname' => 'test');
$format = array('%s');
$where = array('id' => '3');
$where_format = array('%i');
$updateCalc = $db->update($table, $data, $format, $where, $where_format);
?>
The reason of refreshing the page is because you're using a form with submit button, to prevent it just prevent the form to submit
if you have Jquery use the following
//option A
$("form#formId").submit(function(e){
e.preventDefault();
});
and Pure js solution is
document.getElementById('formId').addEventListener('submit', function(e) {
e.preventDefault();
});
Ok have it finally worked. Had the jquery in the ajaxBeheer.php script. Now i have it in the page where the ajax is executed. And that worked for me.
The Jquery link
Is located in the header.
I have now a second screen where the information is updated without a refresh page. :D
It`s without security so thats need too update for everyone that wants too use it! The question was for the second screen no refresh page.
Hopefully i can help some other people with it, becease it was a pain for me too find information.
The whole code:
Page users.php:
<?php
require_once (__DIR__.'/safeuser.php');
require_once (__DIR__.'/include/topheader.php');
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
?>
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
function save(){
// Get the form.
var form = $('#formId');
// Get the messages div. Too show the messages on screen
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// TODO
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
alert (response);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
}
function closeUserVieuw() {
var x = document.getElementById("mainRight");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
document.getElementById("closeUser").style = "display: none;"; // Don`t show the start table
}
}
</script>
<style type="text/css">
</style>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
<!-- FOOTER -->
</div>
</body>
</html>
ajaxBeheer.php:
<?php
// name: ajaxBeheer.php
require_once (__DIR__.'/classes/class-users.php');
require_once (__DIR__.'/include/config.inc.php');
if(isset($_GET['q'])){
$zoek = $_GET['q'];
$param = "$zoek%"; // Zoek alleen op voorletter
$getGebruiker = $db->select("SELECT * FROM users WHERE naam LIKE ?",array($param),array('s'));
?>
<div id="tableUsers">
<div class="headRow" style="" id="tableUsers">
<div class="cell" style="width: 70%">Gebruiker</div>
<div class="cell" style="width: 30%; border-left: 2px solid #fff; border-right: 2px solid #fff;">Status</div>
</div>
<?php
while ($myrow = $getGebruiker->fetch_assoc()) {
if($myrow['active'] == '1'){
$gebrActive = 'Aktief';
} else {
$gebrActive = 'gedeaktiveerd';
}
echo '<a style="display:block" href="?ID='.$myrow['id'].'">
<div class="row">
<div class="cell" style="width: 70%">'.$myrow['naam'].'</div>
<div class="cell" style="width: 30%; border-left: 1px solid #fff; border-right: 1px solid #fff;">'.$gebrActive.'</div>
</div></a>';
}
echo '</div>';
}
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" action="updateUser.php">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="lastname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="useremail" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="userbirthday" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="usertel" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<div class="header" style="margin-top: 5%">
<h3 style="width: 90%; text-align: center;">Uren overzicht</h3>
</div>
<div id="tableUserUren">
<div class="prLeftColomn colomn">
<label>Uren deze week</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren deze maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren vorige maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren Vrij genomen</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label></label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
</div>
<div class="prRightColomn colomn">
</div>
</div>
</div>
<?php
}
?>
updateUser.php
<?php
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
$username = $_POST['firstname'];
// Ready too add the username
$table = 'users';
$data = array('user_name' => $username);
$format = array('%s');
$newJob = $db->insert($table, $data, $format);
if($newJob != $db::SQLSUCCESFULL){ // Variable is 00000
echo 'Er is helaas iets fout gegaan met het toevoegen van de regel. Code:'.$newJob;
header('location: '.$_SERVER['REMOTE_HOST'].'newuser.php?err=DATABASE&code='.$newJob);
exit();
}else{
echo 'succes!'.$username;
}
?>
$query = "select * from comments t1 inner join users t2 on t1.user_id = t2.UserId where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
$(document).ready(function(){
$(".reply").click(function(){
var current = $(this).attr("data-role");
$('.replyForm[data-role="'+$(this).attr("data-role")+'"]').fadeIn();
});
});
</script>
<?php
if(isset($_POST['reply']))
{
echo "<script>alert('$commentid')</script>";
}
?>
<?php } ?>
it is a simple comment system with each comment there is a reply link on click on reply link a textbox is shown . I want to enter comment reply to database table therefore I want to get the record of the specific comment. How to do that with PHP.
this code should do what you want, completely dinamically
<div class="jumbotron comment-container" data-pk="<?php echo $commentid; ?>">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<em class="text-muted"><?php echo $ageDate; ?></em>
</div>
<div class="col-md-12">
<label>Comment by <?php echo $username; ?></label><br/>
<button class="btn btn-primary reply">Reply</button>
</div>
</div>
</div>
And here is the JS part. In order to reduce the code printed in the while loop, the reply form is cloned each time and appended where needed.
var reply_form = $('<div class="row replyForm-container"><div class="col-md-12">'+
'<form method="post" class="reply-form">'+
'<textarea class="form-control" rows="4">Prefilled content</textarea><br>'+
'<br>'+
'<button type="submit" name="reply" class="btn btn-primary" style="float:right" >Reply</button>'+
'</form>'+
'</div></div>');
$(".reply").click(function(){
$(this).hide();
var $container = $(this).closest('.comment-container');
var pk = $container.data('pk');
var rf_clone = reply_form.clone();
rf_clone.find('form').attr('data-pk', pk).data('pk', pk);
$container.append( rf_clone.hide().fadeIn(1000) );
});
// working with dynamical elements, we need to use delegation here
$(document).on('submit', '.reply-form', function(e){
e.preventDefault();
var reply_container = $(this).closest('.replyForm-container');
var pk = $(this).data('pk');
var reply = $(this).find('textarea').val();
console.log('Insert reply "'+reply+'" for comment ID: '+pk);
$.ajax({
type: "POST",
url: 'my_php_handler.php',
async: false,
dataType: "json",
data: {action: 'add-reply', commend_id: pk, reply_text: reply},
success: function (response) {
if( response ) {
reply_container.fadeOut('slow', function(){
var btn = reply_container.closest('.comment-container').find('button.reply');
$(this).remove(); //will remove the element after fadeOut completes
btn.show();
})
}
}
});
});
Check working Fiddle (ajax disabled)
I am developing a Messaging system.I need Scroll bar to be fixed down ,Because when new data arrives It should automatically go down.How to do that in HTML/CSS
Don't mine if this full code is in a unprofessional way..
Home.php
<?php
// Turn off all error reporting
error_reporting(0);
//shop not login users from entering
if(isset($_SESSION['id'])){
$user_id = $_SESSION['id'];
}else{
}
require_once("./inc/connect.inc.php");
?>
<header>
<link rel="stylesheet" href="home - Copy.css" />
<nav>
<h3><a class="h3" href="#">CP</a></h3>
<div><span>Logout</span></div>
<div>
<?php
//Start your session
session_start();
//Read your session (if it is set)
if (isset($_SESSION['user_login'])){
echo '<div id="ull">'.strtoupper($_SESSION['user_login']).'</div>';
}
?>
</div>
</nav>
<body>
<div class="shead">
<div class="a1"> <li >Frequent Member</li>
<div class="fm">
<ul>
<?php
//show all the users expect me
$user_id = $_SESSION['id'];
$q = mysql_query("SELECT * FROM `users` WHERE id!='$user_id'");
//display all the results
while($row = mysql_fetch_assoc($q)){
echo " <div class='usernames'>
<a id=\"usernames\" href='home.php?id={$row['id']}'>{$row['username']}</a>
</div>
";
}
?>
</ul>
</div>
</div>
<div class="a2"> <li >Site's Popular in Your College</li></div>
</div>
</header>
<div class="rss">
<?php
// include('rssclass.php');
//include('rss.php');
?>
</div>
<div class="message-right">
<!-- display message -->
<div class="display-message">
<?php
//check $_GET['id'] is set
if(isset($_GET['id'])){
$user_two = trim(mysql_real_escape_string( $_GET['id']));
//check $user_two is valid
$q = mysql_query( "SELECT `id` FROM `users` WHERE id='$user_two' AND id!='$user_id'");
//valid $user_two
if(mysql_num_rows($q) == 1){
//check $user_id and $user_two has conversation or not if no start one
$conver = mysql_query( "SELECT * FROM conversation WHERE (user_one='$user_id' AND user_two='$user_two') OR (user_one='$user_two' AND user_two='$user_id')");
//they have a conversation
if(mysql_num_rows($conver) == 1){
//fetch the converstaion id
$fetch = mysql_fetch_assoc($conver);
$conversation_id = $fetch['id'];
}else{ //they do not have a conversation
//start a new converstaion and fetch its id
$q = mysql_query( "INSERT INTO `conversation` VALUES ('','$user_id',$user_two)");
$conversation_id = mysql_insert_id($con);
}
}else{
die("Invalid $_GET ID.");
}
}else {
die("Click On the Person to start Chating.");
}
?>
</div>
<script type="text/javascript">
var objDiv = document.getElementById("display-message");
objDiv.scrollTop = objDiv.scrollHeight;
</script>
<div class="send-message">
<!-- store conversation_id, user_from, user_to so that we can send send this values to post_message_ajax.php -->
<input type="hidden" id="conversation_id" value="<?php echo base64_encode($conversation_id); ?>">
<input type="hidden" id="user_form" value="<?php echo base64_encode($user_id); ?>">
<input type="hidden" id="user_to" value="<?php echo base64_encode($user_two); ?>">
<div class="textbox">
<input class="t_box" type="text" id="message" placeholder="Enter Your Message"/>
<button class="t_btn" id="reply">Reply</button>
<span id="error"></span>
</div>
</div>
</div>
<!--
<div class="textbox">
<form action="#" method="post">
<input type="text" name="msg_body" class="t_box" id="t_box" >
<input type="submit" class="t_btn" id="t_btn" name="submit" value="Send">
</form>
</div>-->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
Getmsg.php
<?php
require_once("./inc/connect.inc.php");
if(isset($_GET['c_id'])){
//get the conversation id and
$conversation_id = base64_decode($_GET['c_id']);
//fetch all the messages of $user_id(loggedin user) and $user_two from their conversation
$q = mysql_query( "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'");
//check their are any messages
if(mysql_num_rows($q) > 0){
while ($m = mysql_fetch_assoc($q)) {
//format the message and display it to the user
$user_form = $m['user_from'];
$user_to = $m['user_to'];
$message = $m['message'];
//get name and image of $user_form from `user` table
$user = mysql_query( "SELECT username FROM `users` WHERE id='$user_form'");
$user_fetch = mysql_fetch_assoc($user);
$user_form_username = $user_fetch['username'];
//display the message
echo "
<div class='message'>
<div class='text-con'>
<a href='#''>{$user_form_username}:</a>
<p> {$message}<p>
</div>
</div>
<hr>";
}
}else{
echo "No Messages";
}
}
?>
You didn't mention if you are using jQuery. If yes, you can do something like this:
$('#your_div_id').scrollTop($('#your_div_id')[0].scrollHeight);
Alternatively, only with Javascript you can find solution here:
Scroll to bottom of div?
You always need to pass the height of the div to the scroll option so it is sticked to the bottom. This means that you need to bind this to the event which detects when the new message is received and rendered.
Your solution si based on scrollHeight, these two ling of code can help you
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
You can see this snippet for example, just click on the blue div to add messages
var count = 0;
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
$("body").on("click","#toScrollBottom",function(){
$("#messages").append('<p>Message Line' + count + '<br/>Message line</p>');
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toScrollBottom" style="height: 150px; overflow-y: scroll; margin: 50px; border: solid 2px blue;">
<div id="messages">
<p>Message Line FIRST<br/>Message Line</p>
</div>
</div>
I am in the process of building a blog. My client wants the option of uploading a image when necessary, but not all the time. I wrote the code to do this but I think I missed something. Anybody willing to help me debug is greatly appreciated.
if (!in_array($file_ext,$allowed_ext)) {
$errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
}
The snippet of code above is from the page below and is the error that keeps getting triggered.
if (empty($_POST) === false) {
$allowed_ext = array('jpg','jpeg','png');
if (isset($_FILES['image']) && !empty($_FILES['image'])) {
$file_name = $_FILES['image']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if (!in_array($file_ext,$allowed_ext)) {
$errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
} else if ($file_size > 655360) {
$errors[] = 'File Size to large. Please try a different image';
}
}
if (empty($errors) === true) {
if (isset($_FILES['image']) === true && empty($_FILES['image']) === false) {
$file_name = md5($file_name).'.'.$file_ext;
move_uploaded_file($file_tmp, '../assets/images/'.$file_name);
$image_location = 'assets/images/'.$file_name;
}
$data = array(
'title' => $_POST['title'],
'category_id' => $_POST['category_id'],
'author_id' => $session_user_id,
'author_name' => $user_data['admin_name'],
'summary' => $_POST['summary'],
'contents' => nl2br($_POST['content']),
'image' => $image_location,
'date' => date("F j, Y"),
'time' => date("h:i a e")
);
echo 'Something Cool';
insertPost($db, $data);
header('Location: new.php?success');
}
}
echo '<div id="page-wrapper">';
echo '<div class="row">';
?>
<div class="col-lg-12">
<h1>Write a new post <small></small></h1>
<ol class="breadcrumb">
<li> Dashboard</li>
<li>Write A New Post</li>
</ol>
</div>
</div>
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
$success = '
<div class="alert alert-success">
<h4>Blog Post Successively Submitted</h4>
<p>Your blog post was successfully submitted to the database. Go check it out on the homepage!
</div>
';
echo $success;
} else {
if (empty($errors) === false) {
echo '<div class="alert alert-danger"><srong>After trying to process your request, the following errors occured:</strong>';
echo output_errors($errors);
echo '</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-sm-12">
<div class="form-group">
<label for="title">Title</label><br>
<input name="title" type="text" class="form-control" placeholder="Title of Post" required/>
</div>
<div class="form-group">
<label for="category_id">Category</label><br>
<select name="category_id" class="form-control">
<option value=""> --Select a Category-- </option>
<?php
$query = $db->prepare("SELECT category_id, category_name FROM catagories");
$query->execute();
while ($result = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$result['category_id'].'">'.$result['category_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="summary">Summary</label><br>
<textarea name="summary" class="form-control" rows="3" placeholder="Summary of your post. Keep it short and simple as this is what will be displayed on the homepage"></textarea>
</div>
<div class="form-group">
<label for="content">Content</label><br>
<textarea id="wysihtml5-textarea" class="textarea-wysiwyg form-control" rows="10" name="content" placeholder="Article Contents Go Here"></textarea>
</div>
<div class="form-group">
<label for="image">Image</label><br>
<input type="file" name="image" class="form-control" />
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit Post</button> <button class="btn btn-danger" type="reset">Reset Form</button>
</div>
<?php } ?>
</form>
</div>
<div class="col-lg-6 col-sm-12">
<h3>Posting Guidelines and Restrictions</h3>:
<strong>Restrictions</strong>
<ul>
<li>Images extensions are restricted to JPG's, JPEG's, & PNG's</li>
<li>Image file sizes are limited to 5mb</li>
</ul>
<strong>Guidelines</strong>
<ul>
<li>All the fields are required. Submiting the form with any of the fields left empty will result in errors.</li>
<li>The summary should be kept to less then a single paragraph. It is what is displayed on the homepage.</li>
<li>I'm not really sure what else to put here. Email me if you have any questions.</li>
</ul>
</div><!-- /#page-wrapper -->
<?php
include 'includes/footer.php'; ?>
If conditions are wrong. You are wrongly validating if image is uploaded or not.
Change
if (isset($_FILES['image']) && !empty($_FILES['image']))
To
if (isset($_FILES['image']) && $_FILES['image']['error'] == 0 && $_FILES['image']['size'] > 0)
Also change if condition in similar way, where you are moving/saving image.