AJAX In Symfony 1.2

Prototype will automatically process an AJAX response as long as the correct content-type header is returned.
~/symfony/branches/1.2/lib/plugins/sfProtoculousPlugin/lib/helper/JavascriptHelper.php


/**
 * Returns 'eval(request.responseText)', which is the Javascript function that
 * 'form_remote_tag()' can call in 'complete' to evaluate a multiple update return document
 * using 'update_element_function()' calls.
 */
function evaluate_remote_response()
{
  return 'eval(request.responseText)';
}

This function automatically creates the “request.responseJSON;” object that we use below.

Top of ~/apps/$app/templates/layout.php


<div id="indicator" style="display:none;">Loading...</div>
<h1>Basic letter</h1>
Dear <span>name_here</span>,
Your e-mail was received and will be answered shortly.

Bottom of ~/apps/$app/templates/layout.php


echo link_to_remote('Refresh the letter', array(
  'url'      => 'post/list',
  //'complete' => 'updateJSON(request)',
  'loading'  => visual_effect('appear', 'indicator'),
    'complete' => visual_effect('fade', 'indicator').
                  visual_effect('highlight', 'title').'updateJSON(request);'
));

echo javascript_tag("
function updateJSON(request)
{
  json = request.responseJSON;
  for (var i = 0; i < json.length; i++)
  {
     Element.update(json[i][0], json[i][1]);
  }
}
");

In ~/apps/$appname/config/view.yml


all:
  javascripts: [%SF_PROTOTYPE_WEB_DIR%/js/prototype]

In ~/apps/$appname/modules/post/actions/actions.class.php


class postActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
  }

  public function executeList(sfWebRequest $request)
  {
      $this->setLayout(false);
      sfConfig::set('sf_web_debug', false);
      sfConfig::set('sf_debug', false);

    if ($this->getRequest()->isXmlHttpRequest()) {
        $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
    }
    //$output = array(array("title" => "My basic letter", "name" => "Mr Brown"));
    //return $this->renderText(json_encode($output));

    $output = '[["title", "My basic letter"], ["name", "Mr Brown"]]';
    return $this->renderText('('.$output.')');

  }
}

, ,

No Comments

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!

No Comments