Saturday, November 8, 2014

Ajax autosave selection without submit button




Ajax autosave selection without submit button
1. jQuery library is called
2. The value of  selection in dropdown menu and id are posted
to saveDecision.php, and decsion table in MySQL is updated by ajax post values.
3. The return message is save in div with id autosavenotify
code:
index.php
 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('select.status').on('change',function () {
        var decision = $(this).val();
        var id = $('td.myid').html();
        alert(decision);
        alert(id);
        $.ajax({
                 type: "POST",
                 url: "saveDecision.php",
                 data: {decision: decision, id: id },
                 success: function(msg) {
                     $('#autosavenotify').text(msg);
                 }
      })
  });
});
</script>
<h1>Ajax autosave</h1>
<div id="autosavenotify"></div>
<table width="200px">
    <tr>
    <td class="myid">
        1
    </td>   
        <td><select class="status" >
          <option value='-1'>--Select--</option>
    <option value='approve'>Approve</option>
    <option value='reject'>Reject</option>
    <option value='pending'>Pending</option>
    </select></td>
    </tr>
</table>

SaveDecision.php
<?php
if (isset($_POST['id'])) {
$con=mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
$decision=$_POST['decision'];
$id=$_POST['id'];
    $query = "UPDATE decision SET select_result='$decision' WHERE id=$id";
    $resource = mysql_query($query)
        or die (mysql_error());
    echo 'decision table is successfully updated to '.$decision;   
}
?>

MySQL Database
CREATE TABLE IF NOT EXISTS `decision` (
  `id` int(8) NOT NULL,
  `select_result` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `decision` (`id`, `select_result`) VALUES (1, ' ');

Video: Ajax autosave selection without submit button