A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

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

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();
     }
 
}
This entry was posted in General and tagged , , . Bookmark the permalink.

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

  1. Wenbert says:

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

  2. Pingback: Blog » How to do AJAX in jQuery with JSON callback in Zend Framework

  3. Moe says:

    baseUrl?>/path/to/my/coolaction”

    This didn’t work for me….. this printed

    baseUrl?>/ra_tracking/edit/editTopic

    when I wrote

    alert(“baseUrl?>/ra_tracking/edit/editTopic”)

Leave a Reply to Moe Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>