How to do AJAX in jQuery with JSON callback in Zend Framework

Filed Under (General) by Wenbert on 20-03-2008

Tagged Under : , ,

Here is how to do it in Zend Framework.
Let’s start with the form:

  1.  
  2. <textarea id="mytext">
  3. </textarea>
  4. <input type="button" id="mybutton" value="go" />
  5.  
  6. < script language="Javascript">
  7. //jQuery stuff    
  8. $(document).ready(function() {
  9.     $("#mybutton").click(function() {
  10.         $.post("< ?=$this->baseUrl?>/path/to/my/coolaction",{
  11.             mytext: $(‘#mytext’).val()
  12.         }, function(data){
  13.             //alert("Data Loaded: " + data);
  14.             obj = window.eval(data);
  15.             alert("Saved: "+obj[‘mytext’]);
  16.         },"json");
  17.     });
  18. });
  19. < / script>
  20.  

In your controller-action:

  1.  
  2. public function coolAction()
  3. {
  4.      try {
  5.           if ($this->_request->isPost()) {
  6.                  //Do something that will save the $_POST to the database here.
  7.                  $json = Zend_Json::encode($_POST);
  8.                  echo $json;
  9.           } else {
  10.                  throw new Exception ("Invalid action. Not post");
  11.           }
  12.      } catch (Exception $e) {
  13.             echo $e->getMessage();
  14.      }
  15.  
  16. }
  17.