Submit whole form when select option is changed without reload page - php

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>

Related

Ajax form submission works only once, but I want it to work multiple times

I'm having issue with form submission in ajax, I have a form and I want to send my data to PHP page via ajax and it works fine for the first time.. but once the first record is added to database, then the Submit button does not work,... for inserting new record I've to refresh my page each time.
Why I've to refresh my page for inserting new record ? how to get rid of from this issue ?
Here is my HTML code:
<form id="myForm" action="myInfro.php" method="post" enctype="multipart/form-data">
<label for="name">Book: </label><input type="text" name="name" id="name"><br>
<label for="name">Author: </label><input type="text" name="author" id="author"><br>
<input type="hidden" name="insert" id="insert">
<select id="book_id" name="book_id">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<label for="image">Image: </label><input type="file" name="image" id="image"><br>
<button id="submit_btn">Insert Data</button>
Here is my ajax code:
$("#submit_btn").on("click", function(e){
e.preventDefault();
$.ajax({
url:"myInfro.php",
method:"POST",
dataType:"text",
data:$("form").serialize(),
success:function(data){
$("#result").html(data).fadeOut(2000);
$("#myForm")[0].reset();
load_data();
}
});
here is my function named load_data() - through which I"m fetching data from the server:
function load_data(){
var load = "load";
$.ajax({
url:"myInfro.php",
method:"POST",
dataType:"text",
data:{load:load},
success:function(data){
$("#getData").html(data);
}
});
}

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

Get the select value without refreshing the form

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>

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

multi cloned select menu to submit form using Jquery?

im trying to make a simple form which have a select menu with clone and remove button and once any of those select menus changed it must post the form using .Ajax call .
its working but have some issues
HTML
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" id="lang" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
JS
$(function(){
var counter = 1;
$(".clone").click(function(){
$('#lang').clone().appendTo('#fileds');
counter++ ;
});
$(".remove").click(function(){
if (counter > 1) {
$('#lang:last').remove();
counter-- ;
}
});
$('.lang').change(function(){
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
it have 2 issues
first one when i click the remove button it remove the original select menu first then the cloned one and keep the last cloned one what i need is to remove the cloned menus first and keep the original one
second issue its submit form only when original menu changed what i need is to submit form whenever any menu changed original or cloned.
below is the PHP code from the action PHP page its something simple just to show result
PHP
<?php
print_r ($_POST['lang']);
?>
Thanks
HTML:
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>​
Note: Id of the field has been removed.
JS:
$(function(){
$(".clone").click(function(){
// clone(true) will clone the element with event handlers intact.
$('.lang').last().clone(true).appendTo('#fileds');
});
$(".remove").click(function(){
var selects = $('.lang');
if (selects.length > 1) {
selects.last().remove()
}
});
$('.lang').change(function(e){
// console.log(e)
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});​
Demo:
http://jsfiddle.net/kFB5j/1/

Categories