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

Posted on: Mar 20, 2008 by wenbert

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

<textarea id="mytext">
</textarea>
<input type="button" id="mybutton" value="go" />
 
< script language="Javascript">
//jQuery stuff    
$(document).ready(function() {
    $("#mybutton").click(function() {
        $.post("< ?=$this->baseUrl?>/path/to/my/coolaction",{ 
            mytext: $('#mytext').val()
        }, function(data){
            //alert("Data Loaded: " + data);
            obj = window.eval(data);
            alert("Saved: "+obj['mytext']);
        },"json");
    });
});
< / script>

In your controller-action:

public function coolAction()
{
     try {
          if ($this->_request->isPost()) {
                 //Do something that will save the $_POST to the database here.
                 $json = Zend_Json::encode($_POST);
                 echo $json;
          } else {
                 throw new Exception ("Invalid action. Not post");
          }
     } catch (Exception $e) {
            echo $e->getMessage();
     }
 
}

Subscribe to comments Comment | Trackback |
Post Tags: , ,

Browse Timeline


Comments ( 2 )

[...] Wenbert wrote an interesting post today onHere’s a quick take [...]

Blog » How to do AJAX in jQuery with JSON callback in Zend Framework added these pithy words on Mar 25 08 at 5:13 AM

This has been tested in Internet Explorer (IE) 6 and Firefox. Questions, comments and reactions — just post them here.

Wenbert added these pithy words on Mar 20 08 at 7:10 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!