Update Database Field By Javascript

Dear All,

I developed a receipt printing program which allow user to enter the receipt data and print it. There may be a facility to identify printed receipts.

This is the way I planned to solve this;

  1. Add a Boolean field ‘printed’ to the table receipt

  2. Add a java script to print the receipt

in view :

[i]javascript[/i]

function printDiv(divName) {

     var printContents = document.getElementById(divName).innerHTML;

     var originalContents = document.body.innerHTML;


     document.body.innerHTML = printContents;


     window.print();


     document.body.innerHTML = originalContents;

}


</script>

Button


<div valign="top" align="right"><input type="button" onclick="printDiv('printreceipt')" value="Print" /></div>

  1. Create controller action to set printed=‘1’ of the table receipt

In controller:


 public function actionPrintupdate() {

         $model = $this->loadModel($id, 'Receipt');

        $command = Yii::app()->db->createCommand();

        // build and execute the following SQL:

// UPDATE `tbl_user` SET `name`=:name WHERE id=:id

        $command->update('receipt', array(

            'printed' => '1',

                ), 'id=:id', array(':id' => $model->id));

    

        $this->render('printupdate', array(

            'model' => $model,

        ));

    }

  1. create javascript to execute the action ‘printupdate’

in view:


<script type="text/javascript">

function printupdate() { // I would like to call a url using jQuery?

  $.ajax({

    url: "<?php echo CController::createUrl('receipt/printupdate');?>"

  });

  }

</script>

  1. update onclick event of the button to execute ‘printupdate’;

<div valign="top" align="right"><input type="button" onclick="printDiv('printreceipt');printupdate()" value="Print" /></div>



But the database is not updating. The firebug console report an error as follow";

NetworkError: 404 Not Found - http://localhost/xxxx/xx/index.php/receipt/printupdate"

I tried to solve this by creating fake page named ‘printupdate’ in views --> receipt. But still no lucky.

Your support is highly appreciate.

Thanks,

  • Anil

Hi,

I think that you could use CJuiButton or ajaxLink or ajaxSubmitButton facilities for your use case

Thank you very much luc. Your suggestion help me to learn lot about yii and ajax.

I managed to solve the problem by doing few changes in my controller and view as follows.

Controller:


 public function actionPrintupdate($id) {

       

        $command = Yii::app()->db->createCommand();

        

        $command->update('receipt', array(

            'printed' => '1',

                ), 'id=:id', array(':id' => $id));

    

        ));

    }

View:


<script type="text/javascript">

function printupdate() { // I would like to call a url using jQuery?

  $.ajax({

     url: "<?php echo CController::createUrl('printupdate',array("id"=>$model->id));?>"

  });

  }

</script>

Thanks again.