So basically I am using PHP/AJAX/JavaScript/SQL, and I'm new to it all, to display a list of all my users with a button beside each on that says 'Enable' if there is a 1 in my 'Enabled' column in the database or 'Disable' if there is a 0. The button beside each user displays properly when I first load the page, and if the user has an 'Enable' button, it does enable the user when I click on it, the text changes to 'Disable' but it doesn't disable the user when clicked.
If the user has a 'Disable' button when the page is first loaded, clicking it will change it to blank and the user is not disabled.
I can't figure out where I'm going wrong. I'll include my code so far below.
Code for enable/disable button in adminPage.php
if($enabled=='1'){
$allUsers.='<button id="adminButton_'.$username.'" onclick="adminHandler(\'disable\',\''.$username.'\',\'adminButton_'.$username.'\')">disable</button>';
}
else if($enabled=='0')
{
$allUsers.='<button id="adminButton_'.$username.'" onclick="adminHandler(\'enable\',\''.$username.'\',\'adminButton_'.$username.'\')">enable</button>';
}
adminHandler function in adminPage
<script type="text/javascript">
function adminHandler(action,username,elem){
var conf = confirm("Press OK to '"+action+"' this user.");
if(conf != true){
return false;
}
_(elem).innerHTML = "processing ...";
var ajax = ajaxObj("POST", "Includes/adminProcessing.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "enable_ok"){
_(elem).innerHTML = "Disable";
} else if(ajax.responseText == "disable_ok"){
_(elem).innerHTML = "Enable";
} else {
_(elem).innerHTML = ajax.responseText;
}
}
}
ajax.send("action="+action+"&username="+username);
}
The adminProcessing.php page
if (isset($_POST['action']) && isset($_POST['username']))
{
$username = $_POST['username'];
if($_POST['action'] == "enable")
{
$sql = "UPDATE users SET enabled='1' WHERE username='$username' LIMIT 1";
$query = mysqli_query($conn, $sql);
mysqli_close($conn);
echo "enable_ok";
exit();
}
else if($_POST['action'] == "disabled"){
$sql = "UPDATE users SET enabled='0' WHERE username='$username' LIMIT 1";
$query = mysqli_query($conn, $sql);
mysqli_close($conn);
echo "disable_ok";
exit();
}
AJAX File
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
Your "adminHandler" is being passed "disable", but you're checking for "disabled."
Related
A) I would like to have 2 different functions for 1 button.
For first click function 1 should start, for second click function 2, for third click function 1, fourth click function 2 ...
For now I need 2 buttons, one disables and the other one enables the possibility to input data in a form field. The best would be to have both functions for 1 button (as explained above).
Does anyone has an idea how to do that?
B) All data get saved and can be reopened in the datamanagementsystem. I would like that disabled fields stay disabled (after reopening the form again) for input. Is there a possibility to do so?
<script>
var nav = false;
function disable18() {
document.getElementById("field1").style.color = "red";
document.getElementById("field1").value = "X";;
document.getElementById("field1").disabled = true;
nav = true;
}
function enable18() {
document.getElementById("field1").disabled = false;
document.getElementById("field1").value = "";
document.getElementById("field1").style.color = "black";
nav = false;
}
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
</script>
How I get the data from database:
<?php
session_start();
require_once 'sc/functions.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
// php search data in mysql database using PDO
// set data in input text
$user = "xxx";
$pass = "xxxx";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', $user, $pass); //mysql:host=localhost;dbname=test_db","root","")
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$ID = $_POST['ID'];
// mysql search query
$pdoQuery = "SELECT * FROM dabase WHERE ID = :ID";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your ID to the query ID
$pdoExec = $pdoResult->execute(array(":ID"=>$ID));
if($pdoExec)
{
// if ID exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$ID = $row['ID'];
$field1 = $row['field1'];
}
}
// if the id not exist
// show a message and clear inputs
else{
header( "Location: nodatasearch.php" ); die;
}
}else{
echo 'ERROR Data Not Inserted';
}
} ?>
Submitting/Saving data:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require("php/tc.php");
$ID = $_POST['ID'];
$field1 = $_POST['field1'];
$sql = "UPDATE pdbase SET
field1 = :field1
WHERE ID = :ID";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ID', $ID);
$stmt->bindValue(':field1', $field1);
$stmt->execute();
// var_dump($_POST['user']);
?>
My asnwer will solve problem A however problem B is a little more complicated. You will need a flag for this, for example this is your html
<input type="text" id="field1">
<button id="toggler" class="btn btn-success" onclick="toggleNav()">Toggler</button>
in your js start off with creating your flag, let's set it to false
var nav = false;
When your 1st function is called change your flag to true
function disable18() {
document.getElementById("field1").disabled = true;
nav = true;
}
Now for the second function we will set it back to false
function enable18() {
document.getElementById("field1").disabled = false;
nav = false;
}
Now we create the function that toogles between the 2 of them
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
After that, all that's left is make sure your toggleNav() function is in the onclick() in your button. Now for problem B I have more questions than answers. Need more details about how do you want to do achieve that
I have an HTML form and a JavaScript file that processes the form data (The event onsubmit=validate()). I am trying to use Ajax to send an ID to a PHP script. The PHP script should send back an array (JSON?). Each element in that array will be a column from a query, based on the ID that was sent. Then I want to compare the results found in the database with the one the user entered in the HTML form. My question are: Is this good practice? How can I implement this idea if it is, if not, what is the better approach?
I am putting what I have so far and will add to the morning. I have not been able to find what I am looking for on my own. Here is my code so far:
function validate() {
var first=document.getElementById("b1j").value;
var last=document.getElementById("b2j").value;
var password=document.getElementById("b3j").value;
var ID=document.getElementById("b4j").value;
var number=document.getElementById("b5j").value;
var email=document.getElementById("b6j").value;
var cbox=document.getElementById("check");
if(first.search(/^[aA-zZ]+[aA-zZ]$/) < 0) {
alert("Invalid first name.");
return;
}
if(last.search(/^[a-zA-Z]+[a-zA-Z]$/) < 0) {
alert("Invalid last name.");
return;
}
if(password.search(/(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*()_\-=+<>]).{3,10}/) < 0) {
alert("Invalid password.");
return;
}
if(ID.search(/[0-9]{4}/) < 0) {
alert("Invalid ID");
return;
}
if(number.search(/^(\d{3}[\s\-]){2}[0-9]{4}/) < 0) {
alert("Invalid phone number.");
return;
}
if(email.search(/^\w*#\w{2,5}\.com$/) < 0 && cbox.checked) {
alert("Invalid email.");
return;
}
verify(ID);
}
function verify(id) {
//communicate with the php script
//if not verfied, stay on same page and give an alert saying why the credentials are wrong.
//verfied? Go to the page that is being requested in the options (implement in the php script along with session info)
var xhr = new XMLHttpRequest();
xhr.onload = function () {
//Completely lost beyond here.
const result = JSON.parse(this.responseText);
if (result.found !== 0) {
}
else {
}
};
alert("sending");
xhr.open("GET", "../php/vmc4a4.php?id="+ID, false);
xhr.send();
alert(errorMsg);
}
<?php
//Server info hidden
$con = mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
$query = "SELECT * FROM Stylists WHERE Stylists.id = '$id';";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
}
?>
I need your help to manage a php page with redirection function.
I want my logged in users to redirect to user dashboard instead of displaying login page by typing address in Browser's address Bar. How to prevent users to display login page
Login page codes are given below
<?php
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
I put your codes like this but got no effect. So please elaborate well and give example how to do it exactly.
<?php
include 'dbc.php';
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] = true) {
header('Location: dashboards.php');
}
else {
$_SESSION['status_logged'] = false;
}
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
You already have a session with the user data, so, it's simple, save the status in the same session and make a verification on the top of your script. Like this
Put this in your code
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
And put a verification on the top:
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] == true) {
header('Location: yourDashboardPage.php');
}
else {
$_SESSION['status_logged'] = false;
}
function removeEditor() {
if ( !editor )
return;
document.getElementById( 'inputbox' ).innerHTML = html = editor.getData();
var data=encodeURIComponent(html);
var topic=document.getElementById('currentField').value;
document.getElementById('popup').style.display="block";
document.getElementById('popup').innerHTML="Updating...";
var ajax = ajaxObj("POST", "Report_Viewer.php");
if(topic!=""){
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
document.getElementsByName('btnupdate').item(0).style.display = 'none';
document.getElementById('popup').style.display="block";
document.getElementById('popup').innerHTML=ajax.responseText;
setTimeout(function() {
document.getElementById('popup').style.display="none";
}, 5000);
}
}
ajax.send("data="+data+"&topic="+topic);
}
document.getElementById( 'inputbox' ).style.display = '';
editor.destroy();
editor = null;
}
<?php
if(isset($_POST['data'])){
include_once("php_include/db_conx.php");
$topic= $_POST['topic'];
$comment=($_POST['data']);
$count=str_word_count(strip_tags(strtolower($comment)));
if($count>2500 && ($topic=='introduction' || $topic=='reviewofliterature') ){
echo "Can not save more than 2500 words";
exit();
}else if($count>30 && $topic=='title'){
echo "Can not save more than 30 words as title";
exit();
}else if($count>600 && $topic=='methodology'){
echo "Can not save more than 600 words as Methodology";
exit();
}else if($count>600 && $topic=='objective'){
echo "Can not save more than 300 words as Aims & Objectives";
exit();
}else{
$sql = "SELECT * FROM tbl_synopsis WHERE studentid='$uid'";
$query = mysqli_query($db_conx, $sql);
$num_rows=mysqli_num_rows($query);
if($num_rows>0){
$sql = "UPDATE tbl_synopsis SET $topic='$comment' WHERE studentid='$uid'";
$query = mysqli_query($db_conx, $sql);
echo "Updated";
exit();
}else{
$sql = "INSERT INTO tbl_synopsis(studentid,$topic) VALUES('$uid', '$comment')";
$query = mysqli_query($db_conx, $sql);
echo "Inserted";
exit();
}
}
}
?>
when i enter this line of text to input field
COMPARATIVE STUDY ON EFFICACY OF OMEPRAZOLE WITH PANTOPRAZOLE FOR THE
PREVENTION AND TREATMENT OF NSAIDs RELATED ACID PEPTIC DISODERS.
and press update button which calls removeEditor() function then server stops responding, but when i run this code locally and enter same text in the field then it does work properly. What's wrong with this code or its hosting server's problem?
I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});