Dynamic Form Submission with Ajax

ajaxcontrollersforms

I try to implement a quotation form.
I then created a new module with a phtml file containing the form (with several input / input-select) and the price calculation result.

Now I would like the form to be "dynamic", i.e. that the price is updated each time a parameter (input) is changed and not to have to click on a button to submit manually the form.

I have been told that to avoid a full reload of the page each time a value is changed I had to use Ajax request? Could you confirm please?

How may I implement that?

Thank you for your help,

Best Answer

EDIT: I managed to do it. Here is the solution if it can help :

First the .phtml form:

<form id="form-configurator" class="form-configurator " name="formconfigurator" action="" method="post" enctype="multipart/form-data">

    <div class="item" id="item-1">
        <label class="conf_label">BlaBla</label>
        <div class="inputselect">
            <select class="selector" name="name1" id="input-1"><option value="2" selected="selected">2</option><option value="4">4</option></select>    
        </div>
    </div>

    <div class="item" id="item-2">
        <label class="conf_label">Quantity :</label>
        <div class="inputselect">
            <input id="input-quantity" name="quantity" type="number" value="1" min="1" max="50" style="width: 63px;" maxlength="2" class="input-text required-entry"></input>
        </div>
    </div>

    <strong><span class="devis_Nb" id="Devis_totalF"></span></strong>
</form>

Th JS/ajax script (which send data to php controller and treat the answer):

<script type="text/javascript">
//<![CDATA[
(function($) {

  function doAjax() {
    $.ajax({
        url : "<?php echo Mage::getBaseUrl().'mymodule/index/mymethode' ?>",
        type: "POST",
        data : $("#form-configurator").serializeArray(),
        dataType: 'json',
        success: function(data)
        {
            console.log(data);    
            $("#Devis_totalF").html(data['total_price']);

        },
        error: function ()
        {
        }
    });
  }

// for number type input scan
$('input[type=number]').change(function() {
       doAjax();
    }
  });

// for selectinput scan
$("select").change(function() {
    doAjax();
  });

  //To run script at page load
  doAjax();

})(jQuery);
//]]>
</script>

and the controller.php file:

<?php
class Mine_mymodule_IndexController extends Mage_Core_Controller_Front_Action
{
   public function indexAction()
   {
        $this->loadLayout();
        $this->renderLayout();
   }

   public function mymethodeAction()
   {
    //if ($post = $this->getRequest()->getPost()) {

    $output = array();

    $output = array('total_price' => 10);

    echo json_encode($output);

    }

}
?>