Let's say I have this form :
<form action="Change-status.php" method="post">
<select class="changeStatus" name="changeStatus">
<option value="0">Starting</option>
<option value="1">Ongoing</option>
<option value="2">Over</option>
</select>
<input class="projectId" type="hidden" name="projectId" value="<?php echo $data['id'];?>"/>
</form>
I am currently using this script to submit the form, but it implies refreshing :
$('select').change(function ()
{
$(this).closest('form').submit();
});
What I want to do is to send the form on select change without refreshing the page. I know I have to use AJAX to do so but I couldn't exactly figure out how to implement it.
Could you orient me on how to do this?
Thanks for your help.
EDIT :
After taking comments into consideration, I ended up with the following code :
Html :
<form action="" method="post">
<select class="changeStatus" name="changeStatus">
<option value="0">Starting</option>
<option value="1">Ongoing</option>
<option value="2">Over</option>
</select>
<input class="projectId" type="hidden" name="projectId" value="<?php echo $data['id'];?>"/>
</form>
JS :
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'POST',
url: 'Change-status.php',
data: {selectFieldValue: $('select.changeStatus').val(), projectId: $('input[name$="projectId"]').val()},
dataType: 'html'
});
});
});
PHP :
<?php
include('../Include/Connect.php');
$changeStatus=$_POST['selectFieldValue'];
$id=$_POST['projectId'];
$sql='UPDATE project SET progress="'.$changeStatus.'" WHERE id="'.$id.'"';
mysql_query($sql) or die("Erreur: ".mysql_error());
?>
Getting cross browser
onchange
events and AJAX requests working isn't trivial. I'm recommend you use a javascript framework of some kind, which abstracts away all of the cross browser issues so you don't have to worry about them.Try a js framework
Jquery is just one such framework which has methods such as
.change()
which attaches a handler to the change event for elements like<select>
and.get()
which performs a GET request.Here's a little bit of code to get you started:-
Some references that will be better than my explanations
Please note for this code to work you will need to include the jquery library on you page with a
<script>
tag.See here for a quick start guide on using jquery
And here for a beginners tutorial on how to use jquery's
ajax()
method