jquery autocomplete and get value from mysql onchange - php

I need some help regarding making a form using PHP, MySQL, and jQuery.
Here is my HTML and PHP structure of form:
<form>
<label>Employee Name</label>
<input name="empid" type="text" id="search" <?php if (!empty($empid))echo "value='$empid'"; ?>>
<label>Leave Type</label>
<select name="leavetype" id="leavetype">
<option value="">--SELECT--</option>
<?php Loadlookup("id","leavetype","tbl_leavetypes",$leaveid,$d); ?>
</select>
<label>Leave Balance</label>
<input id="autopopulate" value="">
<input type="submit">
</form>
I am using autocomplete for finding the employee's name. How do I get both the name and ID of employee by autocomplete, and only show the employee's name in input, but the ID in some hidden field? Here is my autocomplete code in PHP:
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql = "select DISTINCT FullName as FullName from prmember where FullName LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$cname = $rs['FullName'];
echo "$cname\n";
and this is the jQuery code for autocomplete:
<script type="text/javascript">
$().ready(function() {
$("#search").autocomplete("search/search.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: true,
});
});
</script>
After that, take a look at my HTML form code. when I change <select> in my form, then I want to auto populate the value of <input id="autopopulate" value=""> from the database.
It will be very helpful if you provide all code.

try the following and check this for more details
$('#leavetype').onchange(function(){
var lvType = $(this).val();
$.get("search.php?q="+lvType, function(data){
$('#autopopulate').val(data);
});
}
);

Related

Updating form fields using AJAX and PHP

Problem: How can I update a form's select input values and text input fields based on a MySQL query after select input's onchange event is fired?
What I've tried:
I have tried to use AJAX with post and get data types, calling a php file that runs the query and echoes the results. Nothing displays. Any errors I have gotten along the way are usually small things that result in server 500 error. I have placed console.log statements in the function that runs the JQuery AJAX request. The change event was detected, the ajax success was called. I also tried using .load(), with GET and POST, no luck either. I have other features that implement AJAX, and I've tried modifying them to fit this scenario and have been unsuccessful.
I also tried to only use a select input that when changed would use AJAX request and .load function to display the other inputs which would be formatted on the php side and echoed to page with selected and values reflecting the db result.
What I want:
I would like a simple example of a form with a select input with three options, text type input, and a submit button. The form is a client backend form to send updates to the MySQL db. Each input represents a filed in the db. The idea is that when the user changes the select inputs selected value, a query is done that uses the selected value for only returning one result. Each field of that one records values in db should now be reflected in the form. First, tell me if this is the correct way to approach this problem, and if not show me how you would.
Example index.php:
<form action="editForm.php" method="POST" enctype="multipart/form-data">
<select id="contact_name" name="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" name="age" placeholder="Age" required>
<input type="text" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
When on change event for #contact_name is fired I need to update the fields with the values the db has.
How would you implement this? Thanks in advance.
Update: as requested here is my JQuery code, but I know my example doesn't use the same names.
<script type="text/javascript">
$(document).ready(function(){
$('#currency_select').on('change', function (e) {
$.ajax({
type: 'post',
url: 'getCurrentValues.php',
data: {currency: 'EUR'},
success: function () {
console.log('ajax was submitted');
}
});
});
});
</script>
Here is my understanding of how to do this:
First, detect event and pass data via ajax for the query to retrieve record. This is in the document ready function to ensure DOM is ready.
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function () {
console.log('ajax was submitted');
}
});
};
editForm.php:
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
$age = $row['age'];
}
<input type="text" name="age" value="<?php echo $age; ?>">
<?php
}
?>
your index:
<select id="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<form action="editForm.php" id="form" method="POST" enctype="multipart/form-data">
<select name="contact_name" id="contact_form" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" id="age" name="age" placeholder="Age" required>
<input type="text" id="race" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
$("#contact_name").on("change", function() {
var selected = $(this).val();
$("#form").load("formdata.php?contact="+selected); //normaly you do that with an id as value
OR
$.ajax({
type:"POST",
url:"formdata.php",
data: {user: selected},
dataType: "json",
success: function(response){
if(response.status == "success") {
$("#age").val(response.age);
$("#race").val(response.race);
$("#veteran_status").val(response.status);
} else {
alert("No data found for this user!");
}
});
});
and in your formdata.php file
//make your db-query
then either make the actual input fields which will be displayed if you use load
OR make something like if you use the ajax version
if($result) {
echo json_encode(array("status" => "success",age" => $result["age"], "race" => $result["race"], "status" => $result["status"]));
} else {
echo json_encode(array("status" => "failed"));
}
also you can delete the action, method and enctype in your form, as this will be set in the ajax function ;)
I would advice you to use the userid as the value in your select field, and you will also need to either also fill the contact_name IN the form OR make an hidden input field so that you can submit the form and know whos data this is..
just echo the $age variable in your editForm.php file and in the AJAX call success function alert the response. like so-
editForm.php
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
echo $age = $row['age'];
}
}
?>
Ajax file
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function (response) {
alert(response);
console.log(response);
}
});
};

Populate input fields with values when option is selected in php mysql

I have a form that i would like to submit details when an option is selected from the database.
The mysql database table :-
USERS contains fields like [email],[age],[name].
I want to be able to populate the other input fields values when one field is selected from the menu.
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="Mark">Mark</option>
<option value="Paul">Paul</option>
<option value="Hannah">Hannah</option>
</select>
<p>
Age
<input type="text" name="age" id="age">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
How do i acheive this using jquery or javascript.
Please Try this,
on your HTML page:
write this to your html page,
<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>
in getUser.php:
getUser.php
<?php
$link = mysqli_connect("localhost", "user", "pass","mydb");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT age,email FROM userstable WHERE name = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;

HTML select POSTing text instead of value for <option> selected

For some reason, a form I am submitting via POST is sending the option text rather than the option value for a form. This is my select declaration:
<select name = "newfreq">
<option val='1'>every week</option>
<option val='2'>every 2 weeks</option>
</select>
When I print out my $_POST array in PHP. I have:
[newfreq] => every 2 weeks
I am particularly new to jquery, which I am using to present the form modally, so I am pasting the full form/div and javascript below in case it's relevant:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(function() {
var dialog, form,
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
});
form = dialog.find( "form" ).on( "submit", function( event ) {
// event.preventDefault();
});
$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
});
</script>
<input id = "create-user" type="submit" tabindex="-1" value = "Change deal" >
<div id="dialog-form" >
<form method = "post" action = "details.php">
<fieldset>
<label for="name">Number of hours</label>
<input type="text" name="newhours" id="name" value = <?php echo $totalhours; ?> class="text ui-widget-content ui-corner-all">
<label for="email">Frequency</label>
<select name = "newfreq">
<option val='1'><?php echo return_frequency($typedeal ,1)?></option>
<option val='2'><?php echo return_frequency($typedeal ,2); ?></option>
</select>
<input type = "hidden" name = "included" value = '<?php echo $included;?>'/>
<input type = "hidden" name = "id" value = '<?php echo $id_bus;?>'/>
<br>
<input type="submit" tabindex="-1" >
</fieldset>
</form>
</div>
return_frequency() is a php function that returns "every 2 weeks" or "every week" depending on the input.
What am I missing here?
<option val='1'> should be <option value='1'>
I know its probably Jquery that confused you since they use .val a lot but actual HTML uses value and so does normal Javascript use .value.
I think since you didn't properly specify a value your browser must be putting the text in value for you somehow. Don't rely on that, however, since I think that's probably a bug and not all browsers will do it.
change to:
<select name = "newfreq">
<option value='1'>every week</option>
<option value='2'>every 2 weeks</option>
</select>

Error posting form values using jQuery in PHP

I have made a simple page which uses jquerydatepicker, two dropdown comboboxes for selecting time values. I tried to post the values but the page gets redirected to itself with selected values shown in url and I get no values on the receiver page.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
var jQueryDatePicker1Opts = {
dateFormat: 'mm/dd/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: true,
showAnim: 'fadeIn'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$('#submit').click(function() {
var startTime = parseInt($('#Combobox1 option:selected').text());
var endTime = parseInt($('#Combobox2 option:selected').text());
if(startTime>=endTime){
alert("End Time should not be less than Start Time !");
return false;
}
});
$("#Campaign_form").submit(function(){
$.post({type:'POST', url:'campaigndata.php' ,
data:$('#Campaign_form').serialize(), success: function(response) {
$('#Campaign_form').find('.form_result').html(response);
}});
var isValid = $.validate.form(this);
return isValid;
});
});
</script>
Here is the form script:
<form name="Campaign_form" id="Campaign_form" >
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/09/2012">
<select name="StartTime" size="1" id="Combobox1" >
<option value="1">01:00</option>
...
<option value="24">23:00</option>
</select>
<select name="EndTime" size="1" id="Combobox2" >
<option value="1">01:00</option>
...
<option value="24">00:00</option>
</select>
<select name="SelectApp" size="1" id="Combobox3" >
<?php
while($row = mysql_fetch_array($result)){
echo "<option value =".$row['AppName'].">".$row['AppName']."</option>";
}
?>
</select>
<input type="submit" id="submit" name="submit" value="submit" >
</form>
Here is the campaigndata.php script:
<?php
$campaignDate = $_POST['jQueryDatePicker1'];
$camp_Start_Time = mysql_real_escape_string($_POST['StartTime']);
$camp_End_Time = mysql_real_escape_string($_POST['EndTime']);
$campaignID = $appid.$campaignDate.$camp_Start_Time ;
?>
This campaigndata.php shows null values on echoing above php variables.
You need to connect to your database before you can use mysql_real_escape_string() and change the form method to post.
You have to return false if you don't refresh page by submitting form
$("#Campaign_form").submit(function () {
var isValid = $.validate.form(this);
if (isValid)
$.post({type:'POST', url:'campaigndata.php',
data:$('#Campaign_form').serialize(), success:function (response) {
$('#Campaign_form').find('.form_result').html(response);
}});
return false;
});
ur answers helped me a lot !!! i figured out the problem was in capaigndata.php
i was using mysql_real_escape_string() before $_POST[''] ;
which was creating problems .
I removed those and used normal $_POST[] and it worked magically !!! :)

Using JSON to select a Dropbox option

I am using Json to retrieve elements from mysql and insert them into form boxes. Displaying in form boxes(text type) was not a problem but in my html one of my form structure is dropbox ... How should i display info that is in the database to the one that is in dropbox??
Here is the code that i used for displaying elements in form type (text). One of them is dropbox in the html.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='rno']").val(json.rno);
$("input[name='url']").val(json.url);
}, "json");
});
</script>
</head>
<body>
<form id="myForm" method="post">
id: <input type="text" name="id"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
<p>title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
Institution: <select name="institution">
<option value="abc">abc</option>
<option value="cdf">cdf</option>
</select>
</form>
<div id="age"></div>
</body>
</html>
PHP part or script_1.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to DB part
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
**//i am not using $row['institution'] (no institution or dropbox part)**
$abc_output = array('title' => $row['title'],'rno' => $row['reportno'],'url' => $row['calc_url']);
}
}
echo json_encode($abc_output);
}
}
?>
Help appreciated.John.
var option1 = new Option("InstitutionName1","InsitutionValue1");
var option2 = new Option("InstitutionName2","InsitutionValue2");
document.myForm.institution.options.length = 0;
document.myForm.institution.options[0] = option0;
document.myForm.institution.options[1] = option1;
This is the way its done normally. In this particular case, you may want to have a for loop or something or jQuery's each(..).
#John
You can put the following snnipet of code at the end of the script tag:
for (item in json.institution) {
$('select[name="institution"]').html('').append('<option value="' + json.institution[item].value + '">' + json.institution[item].text + '</option>');
}
where:
json.institution is a named array that will be returned along with the other form fields by your .php script.
json.institution[item].value is the value of each option.
json.institution[item].text is the text of each option.
The .html('') code is for clear the previous loaded select options.

Categories