I have a problem to displaying some dynamically created data and showing the submitted data when ajax completed.
HTML - form.html
<form name="myForm" id="myForm">
<strong>Skills 1</strong>
<div>
<select name="Skills[]" id="Skills">
<optgroup label="Programming">
<option value="">-</option>
<option value="Javascript">Javascript</option>
<option value="C++">C++</option>
<option value="C#">C#</option>
</optgroup>
<optgroup label="Multimedia">
<option value="Adobe Flash MX">Adobe Flash MX</option>
<option value="Adobe Fireworks">Adobe Fireworks</option>
<option value="Adobe After Effects">Adobe After Effects</option>
</optgroup>
</select>
</div>
<div>
<input type="text" name="SkillsNumber[]" id="SkillsNumber" placeholder="Number of year using" />
</div>
<div>
<select name="SkillsGrade[]" id="SkillsGrade">
<option value="">Select your skills grade</option>
<option value="Noob">Noob</option>
<option value="Amateur">Amateur</option>
<option value="Professional">Professional</option>
</select>
</div>
</div>
</form>
<div id="result-set"></div>
* This select section can be dynamically added (maximum is 3)
jQuery
$(function(){
$("#myForm").submit(function(){
var formData = $(this).serializeArray();
console.log(formData);
$.ajax({
type: "POST",
data: {
theData: formData
},
url: "theresult.php",
success: function(result){
$("#result-set").ajaxComplete(function() {
$("#result-set").html(result);
});
}
});
return false;
});
PHP - theresult.php
<?php
$data = $_POST['theData'];
$enc = json_encode($data, true);
...
....
.....
?>
The question is what should I do, if I have 3 select (so I have 3 Skills, 3 SkillsNumber, and 3 SkillsGrade) and showing it on #result-set. Already cracking head here.
Sorry for bad English. Newb here... :)
add a button on form like
<input type="button" value="submit" id="myBtn">
change your code like this
$("#myBtn").submit(function(){
and write your success function like this
success: function(result){
$("#result-set").html(result);
}
if you want to use json data as a javascript object set your $.ajax method parameter like this dataType: 'json'
Use parse_str to get your data:
PHP - theresult.php
<?php
parse_str($_POST['theData'], $params);
$Skills = $params['Skills[]']; // I am not sure about [] part, test it
$SkillsGrade = $params['SkillsGrade[]'];
$SkillsNumber = $params['SkillsNumber[]'];
echo "Skills: $Skills<br />";
echo "SkillsGrade: $SkillsGrade<br />";
echo "SkillsNumber: $SkillsNumber<br />";
exit;
?>
and add dataType: "html" to your $.ajax() definition
Related
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);
}
});
};
I need to submit the whole form when I change a select option and save it to mysql without reload page.
I have this code, but only POST the select option value and I need to POST the hidden values in the form too.
<form class="form-horizontal" method="POST" action='#' name="dateForm">
<input type='hidden' name='cond_acao' class='form-control' value="edit_seccao_formando">
<input type="hidden" name="id_formando" value="<?=$linha_formandos[id_formando];?>">
<select name="id_seccoes" class="form-control" onchange="return postSelection">
<option selected="selected" value="1">car</option>
<option value="2">boat</option>
<option value="3">plane</option>
</select>
<div id='response_seccoes'></div>
<script>
function postSelection(selectObject) {
var id_seccoes = window.dateForm.id_seccoes.value = selectObject.options[selectObject.selectedIndex].value;
var dataString = "id_seccoes=" + id_seccoes;
$.ajax({
type: "post",
url: "url.php",
data: dataString,
success: function(response) {
$('#response_seccoes').html("ok").fadeIn(100).delay(2000).fadeOut("slow");
//$("#list").html(response);
}
});
return false;
};
</script>
</form>
It's possible to serialize instead of especified the strings?
Can anyone help me please? Thank you
you are using Jquery, I suggest you monitor the select button for change using a jquery function like
$("id_seccoes").change(function(){
//call your post method here.
});
Replace your code with this.
<form class="form-horizontal" method="POST" action='#' name="dateForm">
<input type='hidden' name='cond_acao' class='form-control' value="edit_seccao_formando">
<input type="hidden" name="id_formando" value="<?=$linha_formandos[id_formando];?>">
<select name="id_seccoes" class="form-control">
<option value="1">car</option>
<option value="2">boat</option>
<option value="3">plane</option>
</select>
</form>
<div id='response_seccoes'></div>
<script>
$(document).ready(function(){
$('[name="id_seccoes"]').change(function(){
$.post('url.php',$('[name="dateForm"]').serialize(),function(response){
$('#response_seccoes').html("ok").fadeIn(100).delay(2000).fadeOut("slow");
});
});
});
</script>
I have a problem on passing more than one values from a dropdown menu. What I am doing is an attendance system where a dropdown menu containing the choices of attendance status per student. User will then choose the attendance status of each student accordingly, and what I am trying to do is to pass the status that has been chosen to another page.
I am trying to insert the selected attendance status into an array using AJAX and then pass the array to another page. Here's what I have so far:
todaysattendance.php
//dropdown menu
<tr>
<td> $fetched_fName $fetched_lName </td>
<td> <select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select></td> </tr>
todaysattendance.php
//AJAX code
var tempArr = [];
$("#okselect").change(function()
{
var output = getValues(this, function ()
{
for (var i=0;i<output.length;i++)
{
tempArr.push(output);
};
});
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {tempArr: tempArr},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
add_attendance_check.php
$passed_attstatus = array();
$thestatus = $_POST['tempArr'];
array_push($passed_attstatus, $thestatus);
But from this coding, let's say I took the attendance status for 10 students, I only managed to get the last student's attendance status. I need help on this. Thank you very much in advance!
print variable dropdown_value in add_attendance_check you will get the value of selected dropdown.
<form method="post" action="" role="search">
<select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
jQuery(document).ready(function() {
jQuery("#okselect").change(function() {
var dropdown_value = $('#okselect').val();
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {dropdown_value: dropdown_value},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
});
</script>
I have a great news, I finally solved the problem. All I need to do is to change this line in todaysattendance.php from
<select name='okselect' id='okselect'>
into
<select name='okselect[]' id='okselect'>
In add_attendance_check.php, I simply changed to
$passed_attstatus = array();
$thestatus = $_POST['okselect'];
array_push($passed_attstatus, $thestatus);
No need for AJAX from the very beginning. Anyway I would like to thank everyone who responded. Have a good day!
<select name='okselect' id='okselect' onchange="abc(this.value)">
//your option
</select>
And Ajax call abc function inner abc(value)
This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working
With this code I can see each option value printed but the page is refreshed every time I select an option. The server get the post data correctly, so I just need to do it without refreshing.
Thanks. Regards.
<form action="" method="post">
<select name="day" onchange="this.form.submit();">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<script type="text/javascript">
$('#day').change(function()
{
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
</script>
<?php
include 'day.php'; ?>
day.php
<?php
$day = $_POST['day'];
echo $day;
?>
I think you need this:
e.preventDefault();
//add your id="day"
<select name="day" id="day" onchange="this.form.submit();">
$('#day').change(function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
Update the onchange to call a Javascript function that copies the data to a hidden field in another form, and use Ajax to submit that one instead.
Optionally, you could also submit the data through Ajax directly, without the additional form, but for things that might be done with high frequency, I find it useful to minimize the bandwidth as much as possible.
I could see every option value printed by the <p id=..> without refreshing the page. But the post data is not passed to day.php..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<html>
<head>
<script>
function postSelection(selectObject) {
var day = window.dateForm.day.value = selectObject.options[selectObject.selectedIndex].value;
var dataString = "day=" + day;
$.ajax ({
type:"post",
url: "day.php",
data:dataString,
success: function (response) {
$("#list").html(response);
}
});
return false;
}
</script>
</head>
<body>
<form name="displayForm">
<select name="day" onchange="return postSelection(this)">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<form action="" method="post" name="dateForm">
<input type="hidden" name="day">
</form>
<?php include 'day.php'; ?>
</body>
</html>