Updating form fields using AJAX and PHP - 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);
}
});
};

Related

I can't store all values from user inputs in the array. On window alert only the first array value shows up

I can't seem to save all the clone inputs into an array and pass the array via $.post(). For some reason it only passes the first array value that user selects.
I would like to
pass array by $.Post()
receive true or false if all items in array don't exist in mysql via a php.
I am stuck on the array only holding the value of the original input.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true)
.find("#Equi").val("").end()
);
});
});
$(document).ready(function() {
var ar1 = [];
var input = document.getElementById('#Equi');
$('#Equi').on('change', function() {
// $.post('UnitValidate2.php', {Unit: ar1}, function(data) {
ar1.push(input.value);
window.alert(ar1);
$.post('UnitValidate2.php', {Unit: ar1}, function(data) {
window.alert(data);
if(data == "True") {
window.alert("Move On");
} else {
window.alert("Cant call out unit");
// $("#Equi").val("");
}
});
});
});
<!--for clone -->
<p>
<label for="lname">Eqiupment:</label>
<!--<input type="text" id="Name" name="Name">-->
<input type="text" name="Unit[]" id="Equi" value="" list="namelist4" required/>
<datalist id="namelist4">
<select name="Nam" style="display:none">
<?php
// Include config file
require_once "../Login/config.php";
$conn1 = mysqli_connect($serverName, $userName, $password, $databaseName);
$sql4 = "SELECT * FROM `Status` WHERE Active = 'Yes' AND Status = 'Ready For Rent' ORDER BY Unit ASC";
result4 = mysqli_query($conn1,$sql4);
while ($row4 = mysqli_fetch_array($result4)) {
echo "<option value='".$row4['Unit']."'>".$row4['Unit']."</option>";
}
?>
</option>
</select>
</datalist>
There is still a lot unclear to me. I left out the PHP part where you fill the options in the <select> element. I also made up some elements for your <datalist> element. And ...
Since you are using jQuery you might as well use it properly: I changed your data collecting part to
var ar1=$('.Equi').get().map(el=>el.value);
where I search for all elements of class=Equi (I had to change this from id to class, since Ids must always be unique!), then extract them as a JavaScript Array (.get()), use .map() to get their .value attribute and eventually return the resulting array into ar1.
Since this snippet runs on Stackoverflow I had to comment out the actual $.post() commands but the console.log() shows what would have been posted in it.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true).find(".Equi").val("").end() );
});
$('.Equi').on('change', function(){
var ar1=$('.Equi').get().map(el=>el.value);
console.log("this will be posted:",ar1);
if (false) $.post('UnitValidate2.php',{Unit: ar1}, function(data){
console.log(data);
if(data == "True"){ console.log("Move On ");}
else { console.log("Cant call out unit");}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">add</button><br>
<datalist id="namelist4">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</datalist>
<p>
<label for="lname">Eqiupment
<input type="text" name="Unit[]" class="Equi" value="" list="namelist4" required/>:</label>
<select name="Nam">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
<p></p>

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;

On Dropdown Selection, how to fill complete form fields from Database

How to fill the complete form input fields from Database based on the value selected from the Dropdown
Example: In a Application, by selecting a client name it fills the complete form input fields with the details stored in the Database.
Sample Code:
<select name="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
All the about input fields need to be filled with values on client name selection.
EDIT:
I tried with AJAX but couldn't able get the particular variable from the file... below is my code:
<script>
$(document).ready(function() {
$('#client').change(function() {
alert();
var selected = $(this).find(':selected').html();
$.post('get_details.php', {'client': selected}, function(data) {
$('#result').html(data);
});
});
});
</script>
In the get_details.php file I am storing different values in different variables, but I didn't understand how to get them to individual variable to main page.
This is a just a basic jQuery example that calls itself (the top portion of the script is active when a $_POST is made), which I have named index.php as indicated in the url of the jQuery AJAX. You can use two separate pages to do this if you want. Just separate out the PHP from the HTML/Javascript and change the url: '/index.php':
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
// Exit probably not required if you
// separate out your code into two pages
exit;
}
?>
<form id="tester">
<select name="client" id="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
</form>
<!-- jQuery Library required, make sure the jQuery is latest -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/index.php',
type: 'post',
// This just sends the value of the dropdown
data: { client: $(this).val() },
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
$("input[name='email']").val(Vals.email);
$("input[name='city']").val(Vals.city);
$("textarea[name='address']").val(Vals.address);
}
});
});
});
</script>
When you made ajaxCall return data in json format like
json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
above shown
then parse it in jQuery and put the value in different selectors like
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
above shown.

Update database using Ajax and Jquery

I have a table with multiple rows that lists records from my database.
These records are projects' information and in each row, I have drop down list to modify the status of the project.
To do so, I used Ajax because I hate to refresh the whole page after update.
This is the function I created to do the update:
function call(){
var projid=$('#projid').val();
var projstatus=$('#projstatus').val();
var dataall={'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
}
And below is my drop down list:
<?php do { ?>
<td>
<form action="<?php echo $editFormAction; ?>" method="post" name="form2" id="form2">
<input type="hidden" name="MM_update" value="form2" />
<input type="hidden" name="projid" id="projid" value="<?php echo $row_projlist['projid']; ?>" />
<select name="projstatus" id="projstatus" class="select1" onchange="call()">
<option value="<?php echo $row_status['projstatus'];?>"><?php echo $row_status['sts'];?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
</td>
<?php }while($row_projlist = $projlist->fetch(PDO::FETCH_ASSOC)); ?>
My problem is the following:
When I update the status of the first project, it works but when I try to do it with other projects, it doesn't work.
To be more specific, the parameters of the first project are sent always (this is what firebug says).
Please help!
Your problem is due to duplicate ids. You don't need to use ids(actually do not use id for automatic list generation. Id names must be unique). Remove call function from your select box and use below javascript;
You can use such js to handle that;
$(function() {
$("select[name='projstatus']").change(function() {
var projid = $(this).parent("form").find("input[name='projid']").val();
var projstatus = $(this).val();
var dataall = {'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
});
});
You can see working example for form manipulating part here : http://jsfiddle.net/cubuzoa/SYf8s/
The previous answer will probably solve your problem, but I think it can be simplified.
for the form...
<form>
<select class="select1" onchange="call(<?=$row_projlist['projid']?>)">
<option value="<?=$row_status['projstatus']?>"><?=$row_status['sts']?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
and the javascript
function call(id)
{
$.post('stsproj.php',{'projid':id, 'projstatus':$('#projstatus').val()} )
.done(function(data){
//do something with data
});
}

How to Inform user about ajax submission?

add.php - html markup.
dbadd.php - serverside script,
addpg.js - clientside including AJAX
RSV- form validator
I'm trying to do following: First validate the form (with RSV), if all things right, Then ajax submit (That's why i'm using myOnComplete). Inform user about submission. If user pressed for the first time save button then insert into db. Else update db.
The problems are:
It inserts data into db table but doesn't inform about succes or error
I can't figure out how to insert data into db If user pressed for
the first time save button or update data.
Tried all possible ways. There is no error. Please anyone help me to fix that.
addpg.js
function myOnComplete() {
return true;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Name field required.",
"required,title,Title field required.",
"required,menu, Menu field required",
"required,parentcheck,Parentcheck required",
"if:parentcheck=1,required,parent,Parent required",
"required,content,Page content field required"
]
});
});
$("#submit_btn").click(function () {
CKEDITOR.instances.content.updateElement();
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
if (message != null) {
//do what you like with the message
}
if (err != null) {
//do what you like with the erro
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
});
dbadd.php
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "All right" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
add.php
<div id="add">
<form id="add_form" method="" action="">
<input type="text" name="name" id="name" size="40" value="" class="text-input" />
<input type="text" name="title" id="title" size="40" value="" class="text-input" />
<select name="menu" id="menu">
<option value="" selected="selected">sample</option>
<option value="1">sample 1</option>
<option value="2">sample 2</option>
<option value="0">sample 3</option>
</select>
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
<textarea id="content" style="width:100%" name="content"></textarea>
<input type="submit" name="submit" class="button" id="submit_btn" value="Save" />
</form>
</div>
<script type="text/javascript" src="../../core/includes/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/addpg.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/rsv.js"></script>
For the first problem:
Without actually running the code or seeing a live example, I can't say for sure, but it looks like you have the right idea and it's just a syntax/usage error. For example:
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
Someone please scold me if I'm wrong, but aren't "msg" and "err" found in the JSON (result) rather than in xResponse? result.msg (or result["msg"]) and result.err (or result["err"])
If so, also be aware that I -believe- you will get an 'undefined' error when trying to declare both of those variables since only one of them will be present. You might want to wrap them in try/catch blocks.

Categories