Autopopulate form fields with mysql values based on dropdown selection - php

I have a basic form that I would like to have other fields appear underneath such as email address and job title when the user is selected from the drop down.
The process will be:
User selects name from the drop down
PHP, JQUERY to query mysql database where user is equal to the selection from dropdown
Email address and Job Title fields to appear underneath with populated information.
My JQuery doesn't seem to work on my page...
I have used the code from this Stack Overflow question in which my reply was removed because it was not a 'solution': Populate input fields with values when option is selected - php mysql
Any help on this would be appreciated!
self_submit.html
<html>
<head>
<title>TEST</title>
<script>
$(document).ready(function(){
$('#user').on('change',function(){
var user = $(this).val();
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
async : false,
data : { user : user},
success : function(data) {
userData = json.parse(data);
$('#age').val(userData.age);
$('#email').val(userData.email);
}
});
});
});
</script>
</head>
<body>
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="username1">name1</option>
<option value="username1">name2</option>
<option value="username1">name3</option>
</select>
<p>
Age
<input type="text" name="jobtitle" id="jobtitle">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
</body>
</html>
getUser.php
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_GET['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;
?>
Thanks in advance

you need to change your ajax call to:
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
data : { user : user },
success : function(data) {
userData = json.parse(data);
// $('#age').val(userData.age);
$('#jobtitle').val(userData.jobtitle); // Since you are selecting jobtitle, not age
$('#email').val(userData.email);
}
});
And also you forgot to echo your data:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
exit();
?>
Hope this helps!

Define "POST" method in form tag
download jquery library for offline use or use google cdn or microsoft -then reference it in head html tag
change the data in ajax to data: "user="+user, am used to this format
lastly use proper id names correctly, incorrectly referencing 'ids', you reference in html email id =
$('#jobtitle').val(userData.age);
instead of
$('#email').val(userData.age)
this is fine =>
$('#email').val(userData.email);
$user = $_GET['user']; change to $user = $_POST['user'];
These are some mistake I observed without running you code if still you run into problems ask then

Related

Select "Variable" from DB and display without refreshing the page

Is that possible to select variable in DB (such as : $username) and display their info in textbox ?
Example:
Select : $username
after the selection, in the text input , will show:
$username , $usernameEmail , $usernameContactNumber
and click on "Register", it will insert to database with the information
I have no idea how does this work. I have no problem in inserting value to database.
The only problem that I am unable to solve right now is the condition I needed.
When I choose $username (example: userA),
all the information of userA will be appearing in the text input below
$query = "SELECT * FROM userdatabase";
$result1 = mysqli_query($db,$query);
<select>
<?php while($row1 = mysqli_fetch_array($result1)):; ?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[2];?></option>
<?php endwhile;?>
</select>
The code above is the selection (PHP
<script>
$(document).ready(function(){
$("form#get").submit(function(event) {
event.preventDefault();
var input = $("#username");
$.ajax({
type: "POST",
url: "userregisteraccount.php",
success: function(data) { input.val(data); }
});
});
});
</script>
code above is the ajax
so that when i choose "userName" , "userName" data will be show in the registerform

PHP & jQuery - Create two different textfields with autocomplete having different lists of data retrieved from the database

Customer textfield with autocomplete from database
I succeeded to create one Customer textfield with autocomplete to display customers which start by the text being typed.
index.php for one textfield
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#customer" ).autocomplete({
source: "../phpfiles/search.php",
});
});
</script>
<div class="ui-widget">
<!-- action='./../customer_report_request' -->
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
</table>
</form>
</div>
<?php
//Display the list of customer details
if(isset($_POST['send_customer_request']))
{
include 'db.php'; //connection
$query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'";
$customer_result = $db->query($query);
$count_customer = $customer_result->num_rows;
if($count_customer>0)
{
echo"<div>";
echo "<table>";
echo"<tr>";
echo"<th>Company_Name</th>";
echo"<th>VAT_Registration</th>";
echo"<th>Contact_First_Name</th>";
echo"<th>Contact_Last_Name</th>";
echo"<th>Email</th>";
echo"</tr>";
while ($row = $customer_result->fetch_assoc())
{
echo"<tr>";
echo"<td>".$row['Company_Name']."</td>";
echo"<td>".$row['VAT_Registration']."</td>";
echo"<td>".$row['Contact_First_Name']."</td>";
echo"<td>".$row['Contact_Last_Name']."</td>";
echo"<td>".$row['Email']."</td>";
echo"</tr>";
}
echo "</table>";
echo"</div>";
}
$db->close();
}
?>
Search.php for one textfield
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from customer table
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc()) {
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
?>
The problem is I want to use a single search php file to cater for other queries.
For example:
If a word is typed in the Contact textfield, the query will be
"SELECT * FROM Contact...."
If a word is typed in the Customer textfield, the query will be
"SELECT * FROM Customer...."
Both index.php and search.php were modified to achieve this.
Modified part in index.php
A jQuery variable, component_name was defined. On change from the index.php file, the customer texfield will send the variable to search.php file using a POST method so that it can be identified and used for query purposes.
The contact textfield can be either in the same form in the index.php file or in another php file.
<script>
$(function() {
$( "#customer" ).autocomplete({
var component_name= "customer";
source: "../phpfiles/search.php",
minLength: 1,
change: function(event, ui)
{
$.post("../phpfiles/search.php", data{post_data: component_name});
}
});
});
</script>
Modified search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query="";
if($_POST['post_data']=="customer")
{
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc())
{
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
}
?>
Can anyone help me to achieve this?
I used these links for the jquery-ui and jquery api parts:
api.jquery.com
jqueryui.com
This may be a little complicated ad I hope it helps. Your example does not provide any example data or schema to your DB, so I had to make a number of guesses. You'll need to adjust.
Consider if you have different input fields, you could have:
HTML
<div class="ui-widget">
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input class="entry-field" name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
<tr>
<td>
<label>Contact: </label>
<input class="entry-field" name="contact" id="contact" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request">
</td>
</tr>
</table>
</form>
</div>
JavaScript
$(function() {
$(".entry-field").autocomplete({
source: function(req, resp) {
// determine which field we're working with
var type = $("this").attr("id");
// collect the entry in the field
var term = req.term;
// Prepare our response array
var responses = [];
// PErform POST Request to our Search and accept JSON results
$.ajax({
url: "../phpfiles/search.php",
data: {
t: type,
q: term
},
type: "POST",
dataType: "JSON",
success: function(results) {
$.each(results, function(key, val) {
responses.push(val);
});
}); resp(responses);
},
minLength: 1
}
});
$("#customer_report_request").submit(function(e) {
e.preventDefault();
if ($("#customer").val().length) {
// perform POST to a PHP search for that specific customer details
} else {
// performn a post to a PHP search for that specific contact details
}
// populate result DIV on page with resulting data from POST
});
});
PHP: search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
// get search query
$searchTerm = $_POST['q'];
// get search type
$searchType = $_POST['t'];
//get matched data from customer table
if($searchType == "customer"){
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'");
} else {
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'");
}
/* bind parameters for markers */
$stmt->bind_param("s", $searchTerm);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
if($searchType == "company"){
$data[] = $row['Company_Name'];
} else {
$data[] = $row['Contact_Name']
}
}
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
So there is a lot going on. Will start with your PHP. It was vulnerable to SQL Injection, so I made use of MySQLi Prepare to protect things. We are expecting data to be posted to this script, and we're expecting to conditions: query and type. If we do not get a type, we can set defaults. Might want to add a check for query, but it should always have 1 character.
We get this data to our Search script using the function method for the source option. See more: http://api.jqueryui.com/autocomplete/#option-source
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
So with this, we can add to our $.ajax() call and make use of the error callback. Basically, we've end up sending an empty array back to response.
So we send a send a search term to PHP, we get JSON array data back, we pipe this into our own array to send back to response, and the user will get a list of results.
It's still a little clunky and that's ok if that's what you're users are used to. You can slim it down and also categorize your results. This way you can have one search field. Also once something is selected or the field is change, you can then use AJAX again to pull those details from another PHP that harvests all the data from the DB. This would result in not having to wait for the page to load again etc.
I hope this answer your question and I suspect it will raise more too. Keep searching around, there are lots of answers. Sometimes it's easier to break a big problem down into smaller single questions than to tackle the whole.

Integrating href with $_GET value into a select option

I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.
Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
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;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section

How to display the querying 'DB' for get-variable with multiple values?

I am having a problem while displaying the value in the textbox.
I have check boxes that represent for applying job. When a user checks multiple check boxes and clicks the apply button, the id of the check box value is separated with comma and send to applyView.php file using ajax:
Example: applyView.php?id=1,2,3
and the script is
$(document).ready(function(){
$('.job-apply').on('click', function(){
var selected = $('input[name="job[]"]:checked').map(function(i,e){return e.id;}).get();
var res = selected.join(",");
$.ajax({
url: 'php/applyView.php?id='+res,
dataType: 'json',
success: function(data){
if(data.length > 0)
{
var tmp = data[0];
$('#apply-title').attr('value',tmp.apply_title);
}
window.location.href = "apply.php";
}
});
});
And applyView.php file is:
require "dbconnect.php";
$id = $_REQUEST['id'];
$query = mysqli_query($conn, "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)");
$results = array();
while($row = mysqli_fetch_array($query))
{
$results[] = array(
'apply_title' => $row['job_title'],
);
}
$json = json_encode($results);
echo $json;
Output for the JSON Value is:
[{"apply_title":"Web developer"},{"apply_title":"Software Engineer"},{"apply_title":"Web developer"}]
And apply.php file is:
<form role="form" class="post-resume-form">
<div class="form-group">
<label for="job_title">Job Title</label>
<input type="Text" class="form-control input" id="apply-title" value="" />
</div>
</form>
Now the problem is to display only the value of the id (#apply-title) with separated by comma is it possible.
In the form text box it has to be like this:
"Web Developer","Software Engineer","Web Developer"
Help me out guys!!
If I'm not mistaken, you want to take only the apply title, separated by commas.
Instead of the echo(or beneath it) you can add this code:
$allTitles = "";
foreach($results as $applytitle){
$allTitles = $allTitles . $applytitle["apply_title"] . ",";
}
echo $allTitles;
This should output Web Developer,Software Engineer,Web Developer,.
The last comma(in the output) can be removed with a substring method.
NOTE: I haven't tested this, so it may not work! If you get an error, contact me

Pre Populating a PHP Dynamic Select Option with Stored Session Variable

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

Categories