Use javascript to force a textarea to scroll to end - php

I'm making an instant chat service using PHP and Async javascript. Messages are taken from a database and placed into a text area. The problem is that when messages require the textarea to scroll the setInterval() function used to check and grab new messages forces the text area back to the top of its scrolling height.
I've seen a few solutions and none have worked so far. I tried setting the scrollTop to equal the scrollHeight, but to no avail.
Here's some code:
window.onload = function()
{
if(getUrlVars()['to'] != null)
setInterval(GetMessages, 1000);
}
function ToServer(cmd, data)
{
xmlObj = new XMLHttpRequest();
xmlObj.open('POST','handler.php',true);
xmlObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function()
{
if(xmlObj.readyState == 4 && xmlObj.status == 200)
{
if(cmd == 'cmd=push')
{
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop')
{
document.getElementById('messages').value += xmlObj.responseText;
}
}
}
}
function GetMessages()
{
// Grab account hash from auth cookie
aHash = readCookie('privateChat');
to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
And here's the HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Private Chat</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<h2>Conversation with {%RECIPIENT%}</h2>
<div id="fieldContainer">
<textarea col="10" rows="5" name="messageBox" id="messages"></textarea>
</div>
</div>
<div>
<legend>Message</legend>
<div id="fieldContainer">
<input type="text" id="msgBox">
</div>
</div>
<div>
<input type="button" name="fSend" value="Send message" onClick="SendMessage();">
</div>
<div id="pushResponse">Response</div>
<script src="Chat.js"></script>
</body>
</html>
Thanks!

Related

How to destroy/reset a session with a Form Button in PHP

I'm trying to destroy/reset my session so it cleans the Logs div I created when I press on the Reset Button in my Form. I have assigned a method to my button (btnReset) from a .js file that clears the entire page. Now I just want to make so that it just clears the Logs div where all my calculations are stored at. I have no idea what to do.
Any help would be super much appreciated. SESSIONS is still very new to me so I'm trying my best to understand it. If anyone can explain to me how to properly clear the Logs div after the Reset button has pressed to destroy/reset my session, that would be very much appreciated!
Index.php
<?php
session_start();
if (!isset($_SESSION['results'])) {
$_SESSION["results"] = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Calculator++ with PHP">
<!-- Title -->
<title>Calculator ++ | Calculator</title>
<!-- Favicon -->
<link rel="icon" type="image/png" sizes="16x16" href="Images/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="Images/favicon-32x32.png">
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="CSS/Style.css">
<!-- PHP Files -->
<?php include 'PHP/Calculation.php';?>
</head>
<body>
<!-- Selection for Calculator & Converter -->
<div class="selection">
<div class="titleSelect">Options</div>
<a class="btn-selection" href="Index.php">Calculator</a>
<a class="btn-selection" href="Converter.php">Converter</a>
</div>
<!-- Calculator Container -->
<div class="container">
<div class="result">
<!-- Prints the result -->
<div class="result"><?php echo $Result; ?></div>
</div>
<div class="calculator">
<form action="Index.php" method="POST">
<ul>
<!-- First number -->
<li>
<label for="numberOne"><strong>Number one:</strong></label>
<input class="inputNumbers" type="number" name="numberOne" placeholder="Enter a number">
</li>
<!-- Operation -->
<li>
<label for="operation"><strong>Operation:</strong></label>
<select class="inputNumbers" name="operation" id="operator-list">
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
<option value="sqrt">^</option>
<option value="pow">√</option>
</select>
</li>
<!-- Second number -->
<li id="second-input">
<label for="numberTwo"><strong>Number two:</strong></label>
<input class="inputNumbers" type="number" name="numberTwo" placeholder="Enter a number">
</li>
<!-- Decimal Slider -->
<li>
<label><strong>Decimal: </strong><span id="value_slider"></span></label>
<input type="range" name="slidebar" min="0" max="10" value="0" id="slider" class="slider_style input">
</li>
<!-- Calculate & Reset button -->
<li>
<input class="btn-calculate" type="submit" name="btnCalculate" value="Calculate">
<button class="btn-reset" type="reset" name="resetForm" onclick="btnReset();" value="resetButton">Reset</button>
</li>
</ul>
</form>
</div>
<!-- Logs -->
<div class="logs-container">
<div class="logs-title">Logs</div>
<div class="logs">
<?php echo implode("<br>",$_SESSION["results"]); ?>
</div>
</div>
</div>
<!-- JavaScript -->
<script type="text/javascript" src="JS/HideSecondInput.js"></script>
<script type="text/javascript" src="JS/Slider.js"></script>
<script type="text/javascript" src="JS/Reset.js"></script>
</body>
</html>
Calculation.php
<?php
$Result = 0;
if (isset ($_POST['btnCalculate']) ) {
$numberOne = $_POST['numberOne'];
$operation = $_POST['operation'];
$numberTwo = $_POST['numberTwo'];
if ($operation == '+') {
$Result = ((int)$numberOne + (int)$numberTwo);
$_SESSION["results"][]="$numberOne + $numberTwo = $Result";
}
else if ($operation == '-') {
$Result = ((int)$numberOne - (int)$numberTwo);
$_SESSION["results"][]="$numberOne - $numberTwo = $Result";
}
else if ($operation == 'x') {
$Result = ((int)$numberOne * (int)$numberTwo);
$_SESSION["results"][]="$numberOne * $numberTwo = $Result";
}
else if ($operation == '/') {
if ($numberOne and $numberTwo > 0)
{
$Result = $numberOne / $numberTwo;
$_SESSION["results"][]="$numberOne / $numberTwo = $Result";
} else {
echo "<script>alert('Cannot divide by 0');</script>";
}
}
else if ($operation == 'sqrt') {
$Result = sqrt($numberOne);
$_SESSION["results"][]="sqrt($numberOne) = $Result";
}
else if ($operation == 'pow') {
if ($numberOne and $numberTwo > 0)
{
$Result = pow($numberOne, $numberTwo);
$_SESSION["results"][]="pow($numberOne, $numberTwo) = $Result";
} else {
echo "<script>alert('Please enter a number in both fields');</script>";
}
}
else $Result = 'Unknown';
}
?>
Reset.js
//Resets the entire page when reset button is pressed
function btnReset() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", false);
xmlhttp.send();
window.parent.location = window.parent.location.href;
}
you basically need to adjust your code in the following way:
btnReset should send specific flag for session to be destoryed
btnReset should wait for the request to finish, then do the redirect.
on PHP, you should check for the flag, and if found, delete the session.
function btnReset(event) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", '/index.php?reset=true', true);
xmlhttp.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.parent.location = window.parent.location.href;
}
}
xmlhttp.send();
}
and In PHP (calucations.php):
if(#$_GET['reset'] == true) {
$_SESSION["results"] = [];
session_destroy();
}
of course, this is simple way to do it, you should consider using jQuery https://jquery.com/ which would help you with the AJAX request, and also instead of doing a redirect, you can simple delete the content of the div containing the logs.
Note some typos in your code, file was called "Index.php" it should be case sensitive, so always call it: index.php

Angular $http.post() returning html code

I am trying to do a post request using angular and getting the response as the html code of index.html. I am using zurb's foundation for apps.
<!doctype html>
<html lang="en" ng-app="application">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation for Apps</title>
<link href="./assets/css/app.css" rel="stylesheet" type="text/css">
<script src="./assets/js/foundation.js"></script>
<script src="./assets/js/templates.js"></script>
<script src="./assets/js/routes.js"></script>
<script src="./assets/js/app.js"></script>
</head>
<body>
<div class="grid-frame vertical">
<div class="grid-content shrink" style="padding: 0;">
<ul class="primary condense menu-bar">
<li><a><strong>opt1</strong></a></li>
<li><a ui-sref="pros"><strong>opt2</strong></a></li>
</ul>
</div>
<div ui-view class="grid-content" >
</div>
</div>
</div>
</body>
</html>
home.html is by set as root so it will be displaying a login form
<form ng-controller="LoginController as login" ng-submit="login.loginProcess()">
<div class="grid-block">
<div class="grid-content">
<input type="text" name="username" ng-model="login.user.username">
</div>
<div class="grid-content">
<input type="password" name="password" ng-model="login.user.password">
</div>
<div class="grid-content">
<input type="submit" value="submit">
</div>
</div>
</form>
This is my app.js file
(function() {
'use strict';
var application = angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run() {
FastClick.attach(document.body);
};
application.controller('LoginController',['$scope','$http',function($scope,$http){
this.user = {};
this.loginProcess = function(){
console.log(JSON.stringify(this.user));
var postData = JSON.stringify(this.user);
var config = {method: 'POST', url: '/login.php', data:postData};
$http(config)
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
});
};
}]);
})();
Now as soon as i submit the form I am able to fetch the data properly from the form but it is not being posted properly since the html code of index.html is being displayed in the console when the success function runs.Please suggest a solution so that i will be able to fetch the data from the php file.
<?php
echo $_REQUEST['username'];
?>
and its not working even if I use
file_get_contents("php://input");
In login.php write your php code before any html code starts and add a die() before any html code starts.
login.php
<?php
/*
php code to login
*/
die();
?>
<html>
....
</html>

Modal not validating when elements generated through external file

I've been experimenting with modal dialogue boxes and came across one which uses the FancyBox JQuery tool. I am trying to understand why the validation script works correctly when the modal elements are in HTML form on the same page (in the body tags) as the script, however if I generate these elements in a php file the validation script fails.
Please see my index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="style-modal.css">
<link rel="stylesheet" type="text/css" media="all" href="fancybox/jquery.fancybox.css">
<script type="text/javascript" src="fancybox/jquery.fancybox.js?v=2.0.6"></script>
<script type ="text/javascript" src="like2.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function() {
$(".load").load('show.php');
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var commentid = $("#commentid").val();
alert("clicked!");
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
$("#send").replaceWith("<em>Sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
});
}
});
});
</script>
</head>
<body>
<div class="load">
</div>
</body>
</html>
Please see the php file "show.php" which I load:
<?php
include('connect.php');
echo '<div class="load">
<button class="modalbox" href="#inline">Click</button>
</div>
<div id="inline">
<h3>Enter your email to receive updates</h3>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<input type="hidden" id="commentid" name="commentid" value="5">
<br>
<button id="send">Send E-mail</button>
</form>
</div>
</div>';
?>
In this format when I click "Click" on index.php, the modal appears as normal, however when I click "Send E-mail" with or without data, the modal fades without any feedback or validation. Is it possible to work with this set up? All works as expected when the contents of div id="inline" from show.php are put into the body of index.html. Please assist

JS - submitting through javascript does not pass post variables

I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');

Phonegap ajax and php

I am new to jquery and phonegap and i am un able to find an answer to my question anywhere.
This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="init()">
<div id="launcherPage" data-role="page">
<!-- I'm just here waiting for deviceReady -->
</div>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<div data-role="footer">
<h4>© Camden Enterprises</h4>
</div>
</div>
</body>
</html>
And my Js.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin(){
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
//remove all the class add the messagebox classes and start fading
if(u != '' && p!= '') {
$.post("http://www.myaddress.com/loginlogin.php",{ user_name:$('#username', form).val(),password:$('#password', form).val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
// $.mobile.changePage("some.html");
$.mobile.changePage( "some.html", { transition: "slideup"} );
}
else
{
navigator.notification.alert("Your login failed", function() {});
}
});
} else {
//Thanks Igor!
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;//not to post the form physically
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
Non of this is my own work but from here
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap
I changed the the example to work with php. This is very simple and only for testing purposes
php here
<?//get the posted values
require_once("backend/functions.php");
dbconn(true);
$username = $_POST['user_name'];
if ($username=='Steven'){
echo "yes";
}else{
echo "no";
}
?>
Now this all works and when the conditions are met the page some.html opens.
Now my question is .
How would i send the username of the logged in person to the page some.html?
once confirmed from the php file.
You should be able to access
window.localStorage["username"]
on your some.html page

Categories