I am trying to create a form with an auto-populate feature where a user enters an employee ID, and fields like name, job title, status, etc populate when they leave the employee ID field, similar to the function of the table in http://www.crackajax.net/popform.php#. The data will later be submitted into another database to track other user-entered information. However, when I assemble the files, I can't seem to get the onchange feature to work. Here are the forms:
The form itself:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<form id="entry" name="entry" method="post">
<label for="employeeid" class="stdlabel">Employee ID:</label>
<input type="text" id="employeeID" name="employeeID" onchange="geteedata()">
<br>
<label for="employeename" class="stdlabel">Employee Name:</label>
<input id ="employeename" type="text" name="employeename">
<br>
<label for="employeestatus "class="stdlabel">Status:</label>
<input type="text" name="employeestatus" >
<br>
<label for="employeetitle"class="stdlabel">Job Title:</label>
<input type="text" name="employeetitle" >
<br>
<label for="loccode" class="stdlabel">Employee Loc Code:</label>
<input type="text" name="loccode" >
<input type="submit" name ="submit" value="Submit" style="margin-right:10px">
</form>
<?php
if(isset($_POST['submit'])){
$con = mysql_connect("localhost", "root", "xxx");
if(!$con) {
die("Cannot connect to database:" . mysql_error());
}
mysql_select_db("mydb", $con);
$sql = "INSERT INTO casetracker (emplid,empname,empjobtitle,status, loccode) VALUES ('$_POST[employeeid]','$_POST[employeename]','$_POST[employeetitle]','$_POST[employeestatus]','$_POST[loccode]')";
mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
?>
</body>
</html>
The following is the javascript file:
function geteedata() {
var url = "search.inc.php?param=";
var idValue = document.getElementById("employeeID").value;
var myRandom = parseInt(Math.random() * 99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('employeename').value = results[0];
document.getElementById('employeestatus').value = results[1];
document.getElementById('employeetitle').value = results[2];
document.getElementById('loccode').value = results[3];
}
}
And here is search.inc.php:
if(strlen($param)>0){
$result = mysql_query("SELECT * FROM employee_data WHERE Pernr ='$param'");
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)){
$employeename = $myrow["Last_First"];
$employeestatus = $myrow["Emp_Status"];
$employeetitle = $myrow["Position_Text"];
$loccode = $myrow["loccode"];
$textout .= $employeename.",".$employeestatus.",".$employeetitle.",".$loccode;
}
} else {
$textout=" , , ,".$param;
}
}
echo $textout;
Does anyone have thoughts on what I'm forgetting, missing or doing incorrectly?
Thanks in advance!
It looks like you're not creating an instance of the XMLHttpRequest object before sending off the request.
Try the following:
function geteedata() {
var url = "search.inc.php?param=";
var idValue = document.getElementById("employeeID").value;
var myRandom = parseInt(Math.random() * 99999999); // cache buster
var http = new XMLHttpRequest();
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
Have a look at MDN Using XMLHttpRequest for more information.
Related
I have created a form with live validation in react, but I want to post this form to a PHP page so it gets inserted into the database. The code currently validates but doesn't allow me to access the PHP page, I have access to the SQL database which is on config page and it works well.
react js form
<!DOCTYPE html>
<?php
include ("includes/header.php");
?>
<html lang="en">
<title>Demostration of Forms in React</title>
<script src= "https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src= "https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src= "https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<body>
<h1> Register Page</h1>
<div id="root"></div>
<script type="text/babel">
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
//this.state = {value: 'Write your Name'};
this.handleChange = this.handleChange.bind(this);
this.password = this.password.bind(this);
this.manager = this.manager.bind(this);
this.phoneChange = this.phoneChange.bind(this);
this.emailChange = this.emailChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
//this.setState({value: event.target.value.toLowerCase()});
//perform validation length of the input values or others
//const textval = this.state.value;
var textval = this.state.value;
//if ((textval.length < 5) || (textval.length > 15))
//alert("Your Character must be 5 to 15 Character");
//user validation of the special characters
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < textval.length; i++) {
if (iChars.indexOf(textval.charAt(i)) != -1) {
alert ("Your username should not have !##$%^&*()+=-[]\\\';,./{}|\":<>? \nThese are not allowed.\n Please remove them and try again.");
//return false;
}
}
//if(isNaN(textval))
//alert(textval);
}
phoneChange(event){
this.setState({phone: event.target.value});
var textval2 = this.state.phone;
var iChars2 = "0123456789";
for(var j = 0; j< textval2.length; j++){
if(iChars2.indexOf(textval2.charAt(j)) == -1){
alert("Your phone number should be between 0 and 9");
}
}
}
password(event){
this.setState({password: event.target.value});
}
manager(event){
this.setState({manager: event.target.value});
}
emailChange(event){
this.setState({email: event.target.value});
var emailval = this.state.email;
var emailCheck= "#.";
for(var i =0; j<emailval.length; i++){
if(emailval.indexOf('#')>-1){
alert("Your email must contain an #");
}
}
}
//without .preventDefault() the submitted form would be refreshed
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" id="reg_name" value={this.state.value} onChange={this.handleChange} /><br/><br/>
Email:
<input type="text" id="reg_email" value={this.state.email} onChange={this.emailChange} /><br/><br/>
Phone:
<input type="text" id="reg_phone" value={this.state.phone} onChange={this.phoneChange} /><br/><br/>
Password:
<input type="password" name="reg_password" value={this.state.password} onChange={this.password} /><br/><br/>
Is this an manager account:<br/>
<input type="checkbox" name="reg_manager" value={this.state.manager} onChange={this.manager}/> <br/><br/>
</label>
<br/>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
</script>
</body>
</html>
PHP page to insert database.
<!DOCTYPE html>
<?php
include ("includes/header.php");
$firstname = $_POST['reg_fname'];
//$lastname = $_POST['reg_lname'];
$email = $_POST['reg_email'];
$phone = $_POST['reg_phone'];
$password = $_POST['reg_password'];
//$password2 = $_POST['reg_password2'];
$manager = $_POST['reg_manager'];
if ($manager='on') {
$dbadmin = 1;
}else{
$dbadmin = 0;
}
$query = "INSERT INTO users(firstname,,email,password,manager) VALUES(?,?,?,?,?)";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//prepare and bind
if ($stmt = $dbo->prepare($query)) {
$stmt->bind_param("sssss", $firstname,$email,$hashed_password,$dbadmin);
$stmt->execute();
$stmt->close();
}
?>
<html>
<head>
<title>Registered user</title>
</head>
<body>
<h2>Registered User<?php echo ($firstname) ; ?></h2>
</body>
</html>
you can use axios in react ensuite
after you use his post and get functions ...
via the link of your API or backend
here is an example
axios.post (http://localhost: 8800/ data /, {username: username}). then (res => {
console.log (rec); // for example print : i get username from backen
});
I have the below two files.
How do I get AJAX to populate a label and a value
For example if value is Chicago, IL. How do I get the value to be only Chicago on Submitting the form?
Below the field populates as, for example, Chicago, IL
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center"></h2>
<br /><br />
<label>Search Country</label>
<input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result)
{
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
Below is file TypeaheadTest2.php
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row['city'] . ' ' . $row['state'];
}
echo json_encode($data);
}
?>
If I am getting you right, you are so close to what you are expecting.
I see that you are concatenating the city and state name on the server side. But you want to display only city name on typeahead options.
I would suggest you pass on the city name and state name as separate attributes of an object from PHP and then use them as you want on Javascript side.
Here is the sample code,
PHP:
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$data[] = array('city'=>$row['city'], 'state'=>$row['state']);
}
echo json_encode($data);
}
?>
Javascript:
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result) {
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data) {
result($.map(data, function(item){
return item.city;
}));
}
});
}
});
});
I checked a lot of articles and I don't understand it how to insert data into a MySQL table. What is wrong? I guess that my Ajax request is already wrong.
I would be happy to get help!!!
I did not write programs since 20 years. My coding is for sure not good, but I need to get it running.
Any help would be very appreciated!
The code that follows does not INSERT INTO and does not UPDATE. Why?
Here is the source:
articles.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var lastPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// No submit by onclick
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordInsertWrite()
{
document.getElementById('formheadline').innerHTML = 'Article Database - I save the new item';
document.getElementById("recordWrite").disabled = true;
js_articles[0]=""; // set auto increment id to NULL
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'writearticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr id="buttonarea">
<td align="right" colspan="2">
<hr noshade="noshade" />
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value=" Save New Record " onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div id="aside">
</div>
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
</body>
</html>
writearticle.php
<?php
$link = mysql_connect('test.test.com:3306', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
// Escape user inputs for security
$ID = mysql_real_escape_string($_POST['ID']);
$Item = mysql_real_escape_string($_POST['Item']);
$ItemCategory = mysql_real_escape_string($_POST['ItemCategory']);
if('$ID' == '')
{
$sql = "INSERT into articles values(NULL,'$Item','$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("error");</script>';
}
else
{
echo '<script type="text/javascript">alert("ok");</script>';
}
}
else
{
$sql = "UPDATE articles SET Item='$Item',ItemCategory='$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("update error");</script>';
}
else
{
echo '<script type="text/javascript">alert("update ok");</script>';
}
}
?>
I'm trying to submit Multiple Form Items from HTML using Java-script into mySQL via AJAX request. I can get one field to update but not the other 2. I've commented out the other code I believed would aid in this but was not working.
HTML part:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
parameters = 'fname='+document.getElementById('fname').value;
xmlhttp.open("POST", "update.php", true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
} ;
</script>
</head>
<body>
First Name: <input class="work" type="text" id="fname" ><br>
Middle Name: <input class="work" id="mname" type="text"><br>
Last Name: <input class="work" id="lname" type="text"><br>
<input type="button" value="Submit" onclick="insert();">
<div id="message"></div>
</body>
</html>
PHP part:
<?php
//require 'connect.midasproject.php';
$conn_error = 'could not connect.';
$dbhost = "localhost";
$dbname = "mastergolddb";
$dbuser = "root";
$dbpass = "";
if (!#mysql_connect("$dbhost", "$dbuser", "$dbpass")||!#mysql_select_db ("$dbname")) {
die($conn_error);
} else {
echo 'connected.';
}
$fname = $_POST['fname'];
//$mname = $_POST['mname'] ;
//$lname = $_POST['lname'];
if (!empty($fname)) {
$query = "INSERT INTO `customers` VALUES ('','$fname','joe','blow')";
if ($query_run = mysql_query($query)) {
echo 'data inserted.' ;
} else {
echo 'Query failed.';
}
}
?>
you need to pass all 3 values to the ajax function. you seem to be passing just fname here
parameters = 'fname='+document.getElementById('fname').value;
I'm trying to populate a third set of radiobuttons as an addition to the following script: http://www.electrictoolbox.com/json-data-jquery-php-radio-buttons/
For some reason I cannot seem to fill the third set with the corresponding data. It just stays blank :(
Calling the populateFruittype() function only gives back [ ], while populateFruitVariety() returns the json data correctly.
getdata.php (DB connection / fetching data)
<?php
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "username";
$password = "password";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE variety = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function populateFruitVariety() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('getdata.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitVariety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
}
function populateFruittype() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
$(function() {
$('input[name=fruitName]').change(function() {
populateFruitVariety();
});
});
$(function() {
$('input[name=fruitVariety]').change(function() {
populateFruittype();
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>
The DB query and content can be found here: http://www.electrictoolbox.com/mysql-example-table/
Just add:
`fruittype` varchar(50) NOT NULL
and fill it with some custom values.
Problem solved.
.change(function() had to be .live('click', function()