Trigger AJAX function on form loaded from mysql/php - php

I have a drop down menu that is populated from a mysql table via php. When an item is selected a second drop down menu is triggered using a variable from the first form. This works as expected when making a selection via onchange trigger.
I would like to change this though, and have the script fire when the drop down is loaded and the selected item (set from previous page) is pre-set, I dont want any user interaction.
Here is the form code
<div><select class="form-control m-b" name="id" onChange="get_engineers(this.value)" style="font-family: monospace">
<?php
$qry = "SELECT id,name FROM products WHERE Parent_team = $parent_team ORDER BY name" ;
$stmt = $mysqli->prepare($qry);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
if($product==$row['name']){
$selectCurrent='selected';
}else{
$selectCurrent='';}
echo '<option value="'.$row['id'].'" '.$selectCurrent.'>'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
And the second form drop down
<div class="form-group"><label class="control-label">Engineer</label>
<select class="form-control m-b" name="engineer" id="engineer" style="font-family: monospace">
<option selected="selected">--Select Engineer--</option>
</select>
</div>
And the script
<script>
function get_engineers(id)
{
$.ajax({
type: "GET",
url: "ajax_engineers.php", /* The engineer id will be sent to this file */
beforeSend: function () {
$("#engineer").html("<option>Loading ...</option>");
},
data: "id="+id,
success: function(msg){
$("#engineer").html(msg);
}
});
}
</script>
I tried onload instead of onchange but nothing happens.
thanks

First, add an id attribute to your first select:
<select id="my-unique-id" class="form-control m-b" name="id">
Then you can trigger it via the jQuery onload like so:
<script>
$(function(){
// This will run it on page load to catch any auto-filled values
get_engineers($('#my-unique-id').val());
// This will run it when the value is changed
$('#my-unique-id').change(function(){
get_engineers($(this).val());
});
});
</script>

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);
}
});
};

Dropdown onchange using ajax

I have a dropdown in my form which I used to filter data. I am using ajax onchange function to filter the data based on the selected list.
My dropdown looked something like this :
<select id="opt_level" name="opt_level">
<option value="level1">Level 1</option>
<option value="level2">Level 2</option>
<option value="level3">Level 3</option>
</select>
And here is the div that I wanted to display the onchange data :
<div id="opt_lesson_list">
<!-- Some statement here -->
</div>
When there is onchange on dropdown, it will go through this ajax function :
jQuery(document).ready(function($) {
$("#opt_level").on('change', function() {
var level = $(this).val();
if(level){
$.ajax ({
type: 'POST',
url: 'example-domain.com',
data: { hps_level: '' + level + '' },
success : function(htmlresponse) {
$('#opt_lesson_list').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
And going to the url example-domain.com to check if there is post made from ajax :
if(isset($_POST['hps_level'])){
// Statement to select from database
}
So after filtering done, data inside the <div id="opt_lesson_list"></div> should display the filtered data. But what happened is, the ajax response to the whole page which means that my whole form is multiplying and displayed in the div that I used to display onchange data.
EDIT
My PHP is just filtering data from database based on the value selected :
if(isset($_POST['hps_level'])){
$sql = "SELECT DISTINCT(hps_lessons) FROM holiday_program_setup WHERE hps_level = '".$_POST['hps_level']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<ul class="list-unstyled subjects">';
echo '<li class="bordered" style="width: 30%;">';
echo $row['hps_lessons'];
echo '</li>';
echo '</ul>';
}
}
$sql = NULL;
}
If I echo $_POST['hps_level']; I can get the value of the dropdown selected.
my whole form is multiplying and displayed in the div that I used to
display onchange data.
It seems like you are pointing your ajax url example-domain.com to the page where all your html page is and the ajax returning the whole html page to your div response <div id="opt_lesson_list"></div>.
Try to create another blank php page and put your php isset code in the new php file.
if(isset($_POST['hps_level'])){
// Statement to select from database
}
Replace your ajax url with the new php file url. By doing that, your ajax will grab all the data from the new file and display in your response div.
your provide valid url,becz data filter to hps_level
jQuery(document).ready(function($) {
$("#opt_level").on('change', function() {
var level = $(this).val();
alert(level);
if(level){
$.ajax ({
type: 'POST',
url: 'example-domain.com',
data: { hps_level: '' + level + '' },
success : function(htmlresponse) {
$('#opt_lesson_list').append(htmlresponse);
alert(htmlresponse);
},error:function(e){
alert("error");}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="opt_level" name="opt_level">
<option value="level1">Level 1</option>
<option value="level2">Level 2</option>
<option value="level3">Level 3</option>
</select>
<div id="opt_lesson_list">
<!-- Some statement here -->
</div>

Autosave from php to mysql without page change or submit button

Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

Load <select> options via a MySQL table, and allow the user to add to it via jQuery

I have a MySQL table which looks like this:
ID OPTION
1 First
2 Second
The user sees the following:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
</select>
</div>
I would like the user to have the option to insert into the table, as follows:
<div id="add">
<input type="text" name="newOption" placeholder="Your own option">
<input type="button" value="Add">
</div>
It would then select their newly-added option:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3" selected>Third</option>
</select>
</div>
As the above code is part of a page which contains other form elements the page can't be reloaded, otherwise the data they've already typed will disappear. So I'd like to use jQuery.
EDIT: I have tried the following but it adds rows twice, sometimes even four times, for reasons I cannot fathom!
$("#button").click(function(){
var test = $("#<?php echo $selectName; ?>").val();
var dataString = 'select=<?php echo $select; ?>&selectName='+ test;
$.ajax({
type: "POST",
url: "optionAdd.php",
data: dataString,
cache: false,
success: function(html){
$("#<?php echo $select; ?>List").load("optionList.php?select=<?php echo $select; if ($_GET[required] == "no") { echo "&required=no"; } ?>");
}
});
});
The reason for the PHP above is I want to use multiples of this code on the same form and so I'm using GET to select the options, as it were.
You would need to send an AJAX request to server with the new data and get an ID returned for this new option. Once the ID is received you can create the option with the new ID as value and the user defined text
$('#add button').click(function(){
/* get value from previous input*/
var newOpt=$(this).prev().val();
/* make AJAX "POST" request*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( newId ){
/* ajax successfully completed, add new option*/
$('#options select').append('<option value="'+ newId +'">'+newOpt+'</option>');
});
return false; /* prevent browser default handling of button click*/
})
At server receive the data as you would a form field with name="newOption" ie $_POST['newOption'] and send back a new ID as text
Alternatively you could send back all the options as html in sort order you want and replace all the options in the select.
/* ajax to replace all options with html from server*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( response ){
/* ajax successfully completed, add new option*/
$('#options select').html( response);
});
I would suggest using jQuery AJAX to call a PHP Script to store the new option to the database, that returns the new ID and the given option name on success and then add the new entry to the <select> using Javascript.

Categories