So basically I have a intranet for a business where the employees can login and do various tasks. In order to inprove efficency I have implemented what I am calling the "QuickTask" feature where the employees can select a task via a drop down menubefore they log in so it can go straight to it. Due to there being various departments, I have made a script where the employees can type in their username and press the submit button it populates the list of tasks relevant to their department, this is only temporary as the submit button needs to be used to actually login. However, I would like to change this so the list would populate as they type their username. How could I do this?
I have 3 files.
1. index.php (Log in page)
2. quickTask.js (jQuery function)
3. determine_department.php (The file quickTask.js is communicating with)
Here is the code:
index.php:
<form action="javascript:void(0);" method="post">
Username: <input type="text" id="username" name="username" /><br />
Password: <input type="password" name="password" /><br />
<i>QuickTask:</i><div id="quickTask"></div>
<br />
Forgot Password?<br />
<input class="test" type="submit" id="thing" value="Log In" />
</form>
quickTask.js
$(document).ready(function() {
$('input#thing').on('click', function() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('../inc/determine_department.php', {
username: username
}, function(data) {
$('div#quickTask').html(data);
});
}
});
});
determine_department.php:
<?php
$username = $_POST['username'];
if(isset($username) === true && empty($username) === false) {
mysql_connect("localhost", "root", "24Bottlesofgin24");
mysql_select_db("intranet");
$sql = "SELECT DEPARTMENT FROM `employees` WHERE USERNAME='$username'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$depID = $row['DEPARTMENT'];
}
$sql2 = "SELECT * FROM `quicktask` WHERE DEP_ID='$depID'";
$result2 = mysql_query($sql2);
echo "<select name=\"QT\">";
echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
while($row2 = mysql_fetch_array($result2)){
echo "<option value=\"" . $row2['DEP_ID'] . "\">" . $row2['TASK'] . "</option>";
}
echo "</select>";
}
?>
Here is a live example:
Here is what you want, converted from How to delay the .keyup() handler until the user stops typing? to your needs. It will run the query if/when the user stops typing for 200 ms, the time is set by the second parameter to delay, you can have it for any amount of time you like. However, I am really with those who suggest using an autofill plugin - why reinvent the wheel?
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function() {
$('input#username').on('keyup', function() {
delay(function(){
var username = $('input#username').val();
if($.trim(username) != '') {
$.post('../inc/determine_department.php', {username: username}, function(data){
$('div#quickTask').html(data);
});
}
},200)
});
});
$('input#username').on('keyup', function() {...});
but better be sure to only run a single ajax request at a time.
Change
$('input#thing').on('click', function() {
to
$('input#username').on('keyup', function() {
Should do it, you want the keyup event on the #username input instead of the click event of #thing
Basically, the click function will still them same. You just need to affect it to the keyup event of your username input :
$('#username').keyup( function() {
var username = $('input#username').val();
if($.trim(username) != '') {
$.post('../inc/determine_department.php', {username: username}, function(data){
$('div#quickTask').html(data);
});
}
});
javascript:
$('input#thing').keyup(function()
mysql:
$sql = "SELECT * FROM `quicktask` WHERE DEP_ID IN (SELECT DEPARTMENT FROM `employees` WHERE USERNAME like '".$username."%')";
$result = mysql_query($sql);
echo "<select name=\"QT\">";
echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
while($row = mysql_fetch_array($result)){
echo "<option value=\"" . $row['DEP_ID'] . "\">" . $row['TASK'] . "</option>";
}
echo "</select>";
Related
Im having an issue with form method.
How can I insert a form value in the database in different table by language select.
I have in my database the tables called article_en / articles_ro ,and when I chose with select english I want the values to be inserted in the article_en
Also when I select the language its not staying selected.
And if I write something in the inputs and chose a language the inputs are being cleared.
PS:Im a newby , I am still learning.
This is the language select code
<?php
define("LANG",$_GET['lang']);
include('../db.php');
function select_langs(){
global $conn;
echo'<h2 class="box-title">Select the language where you want to the article</h2>
<select id="select_language">
<option selected disabled hidden value=""></option>';
$get_languages = mysqli_query($conn, "SELECT lang,title from `languages`") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($get_languages)){
if($row['title'] == $_GET['lang']){
echo'<option value="insert_article.php?lang='.$row['lang'].'" selected>'.$row['title'].'</option>';
}
else{
echo'<option value="insert_article.php?lang='.$row['lang'].'">'.$row['title'].'</option>';
}
}
echo'</select>';
}
?>
And this is the insert code.
<?php
include('./lang.php');
include('../db.php');
define("LANG",$_GET['lang']);
select_langs();
// extract data from form; store in variable
$title = $_GET['title'];
$link = $_GET['link'];
if (!empty($title) and !empty($link ) and !empty($_GET['lang'])) {
// Define the query to inser the song request
$sql = "INSERT INTO `articles_".LANG."`(title , link)VALUES (".$title.", ".$link.")";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#select_language").bind("change",function(){var n=$(this).val();return""!=n&&(window.location=n),!1});
</script>
<form action="insert_article.php" method="get">
<label id="first">title:</label><br/>
<input type="text" name="title"><br/>
<label id="first">link:</label><br/>
<input type="text" name="link"><br/>
<input type="submit" value="submit">
</form>
Thank You.
I think you need to use ajax to send the details to the php to insert it in your database. It's just easier.
var select_language= document.getElementById("select_language").value;
var title= document.getElementById("title").value;
var link= document.getElementById("link").value;
var data= {select_language: select_language,title: title,link:link};
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function(html)
{
console.log (html);
alert("Success");
},
error: function (html)
{
console.log (html);
alert("Failure");
}
});
insert.php
include '../dbconfig.php';
$select_language= mysqli_real_escape_string($db,$_POST['select_language']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$link= mysqli_real_escape_string($db,$_POST['link']);
$query = "your insert query";
mysqli_query($db, $query) or die(mysqli_error($db));
Hope this helps.
Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});
Code Logic:
1) User types in username and password, user clicks submit.
2) jQuery script pulls the php script below.
3) jQuery determines which php value is returned.
4) if value 1 is returned, jquery and php will process what's in the if statement.
5) if value 0 is returned, jquery and php will process whats in the else statement.
How do I successfully make the code below work alongside the logic above? I can't seem to make a connection in my mind.
class1.php
$email = mysql_real_escape_string(strip_tags($_POST["username"]));
$password = sha1($_POST["password"]);
$sql = "SELECT * FROM users WHERE username = '{$email}' AND password = '{$password}'";
$result = mysql_query($sql) or exit("ERROR: " . mysql_error() . "<br>IN QUERY: " . $sql);
if (mysql_num_rows($result) > 0) {
return 1;
$row = mysql_fetch_array($result);
$_SESSION["userid"] = $row['user_pid'];
} else {
return 0;
$userid_generator = uniqid(rand(), false);
mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')");
$id = mysql_insert_id();
$leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'");
while($rows = mysql_fetch_array($leaders)) {
if ($rows['is_leader'] == 'yes') {
$leader_id = $rows['user_pid'];
mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type)
VALUES('$leader_id', '$userid_generator', NOW(), 'full')");
echo "new user created and logged in";
}
$_SESSION["userid"] = $userid_generator;
}
}
?>
index.html:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.loading {
float:right;
background:url(img/ajax-loader.gif) no-repeat 1px;
height:28px;
width:28px;
display:none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var username = $('input[username=username]');
var password = $('input[password=password]');
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "processing/class1.php",
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
alert('success');
//if process.php returned 0/false (send mail failed)
} else { alert('failure');
}
});
return false;
});
});
</script>
<input type="text" id="username" name="username" />
<input type="password" id="password" name="password" />
<input type="submit" id="submit" />
<div class="loading"></div>
<div id="display"></div>
Ajax is effectively a "blind client". So, think of what you would see if you were to manually view the php script, and interpret that as what your ajax callback would be parsing.
Having said that, the "0/1" return you're looking for is dependent on one (of many) echos going on in your script (most notably the following):
echo "new user created and logged in";
if you want the ajax callback to recognize a 0/1, this would need to only echo a "1" (not verbiage), where as errors would simply return a "0" (such as your or exit("ERROR...).
EDIT
Also, looking further, your var data = 'name=' component (assuming you want it to align with the PHP $_POST["username"]) should probably be renamed to var data ='username=' (the data property of the ajax call is what' populating your PHP's $_POST variables, so names need to align).
I am getting no responses when I try to fire this ajax request from jquery:
/********************************
CHANGE USER SETTINGS
*********************************/
$(".submitUserSetting").live('click', function() {
//get values
var department = $("#us_department").val();
var sortOrder = $("input[#name=us_sortOrder]:checked").val();
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
}
});
});
I mean nothing. No javascript errors, no errors on the MySQL query, not even POST data in the console.log. Just a taunting batch o' silence. Even if I comment out all the code in the PHP page and just echo the data I sent over to it, nothing. Here's the PHP page (the class exists, the functions work, I'm using them on a dozen or so other pages)
<?php
require_once("../classes/mysqlconnect.php");
$db = new dbconnect();
$db->makeConnections("TimeSheetManager");
$empname = $_POST['empname'];
$department = $_POST['department'];
$sortOrder = $_POST['sortOrder'];
//get the department id
$dQuery = "SELECT id FROM departments WHERE department = '" . $department . "'";
$dResults = $db->getResults($query);
if (mysql_num_rows($dResults) > 0) {
while($rows = mysql_fetch_array($dResults) {
$deptID = $rows['id'];
}
}
//update database
$query = "UPDATE users SET `department` = '" . $department "', `displayOrder` = '" . $sortOrder . "' WHERE username = '" . $empname . "'";
$results = $db->getResults($query);
if ($results) {
echo "!success";
} else {
echo "!fail";
}
?>
Here's the form code:
<div id="userSettingsForm">
<form name="userSetting">
<p><label for="sortOrder">Display Order:</label></p>
<p class="userSettingElement">Oldest First <input type="radio" name="us_sortOrder" value="asc"> Newest First <input type="radio" name="us_sortOrder" value="dsc"></p>
<p><label for="us_department">Department:</label></p>
<p class="userSettingElement">
<select id="us_department" name="us_department">
<option value="null">Select A Department</option>
<?php
$query = "SELECT * FROM departments";
$results = $db->getResults($query);
while($row = mysql_fetch_array($results)){
if (count($results) > 0) {
//get department and id
$department = $row['department'];
$deptID = $row['id'];
print "<option value=\"" . $deptID . "\">" . $department . "</option>";
}
}
?>
</select>
</p>
<p>Submit</p>
</form>
</div>
Thanks for all the help and suggestions. I rebooted Firefox and the error was in empname, I wasn't setting it (doh!). Beluga was on to that but it took a bit for it to dawn on me. Wish I could award everyone with the answer.
How can you tell you're not getting an error? Add an error handler to your .ajax() call:
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
OK, some more investigation shows that the error is actually in a peculiar combination of pieces of code that you are using.
Apparently, href="javascript:void(0)" prevents event propagation. The event is triggered on the element itself (so handlers bound with .click(fn) work) but ancestor elements are not notified of the event.
Since you are using the .live() method, which relies upon event propagation, this doesn't work here.
I would suggest the following instead:
Submit
and JS:
$(".submitUserSetting").live('click', function(e) {
e.preventDefault(); // disable the link action
[snip]
});
See jsFiddle demonstrating this.
The issue is the way you send the data.
Try enclosing the property in { } 's and changing the variable format to
{ "propertyName" : "value", "propertyName" : "value" }
i.e
data: { "empname" : empname ,"department" : department, "sortOrder" :sortOrder }
alternatively if it is a form you can even say
data : { $("#form").serialize() }
you need to return some value in your php function
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
define empname in your call which is missing.
this gives you Uncaught ReferenceError
My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
jQuery (insert generated HTML/wait for action)
PHP (generate html)
Go back to step 1)
(EDIT: Corrected an error and changed script to answer)
PHP
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});
place all your event-handlers outside the ajax function and use the live() method instead. And you need to include what data to send when using ajax. From visualjquery:
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});
I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to this question dealing with similar problem.
Like peirix and TheVillageIdiot pointed out, the live plugin maybe useful. However, there are some other things you may got wrong in your code:
First, your HTML isn't valid. You have to put quotes around attribut values. You could do this within quotes by escaping inner quotes with a backslash:
echo "<input type=\"text\" class=\"inputfield_visible\" />";
since this looks not that nice, you could leave the PHP part and write pure HTML if you change this:
<?php
...
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
To that (IMHO by far more readable):
<?php
...
?>
</tbody>
</table>
<input type="text" class="inputfield_visible" />
<button class="new">Neu</button>
Secondly, and that seems to be even more important, it looks to me like you have a SQLInjection vulnerability, because you pass the field values directly to mysql without using mysql_real_escape_string first. I'm not that into PHP, so maybe I got that wrong, but what happens if you enter ';-- into you input fields?