tags:

views:

21

answers:

1

I have a subscription link on a page that the logged in users can use.

Toggling the link on the page is no issue, as I can do a .post and echo out what the PHP returns

if ($subscription == true) {
  echo 'Subscribed';
} else {
  echo 'Click to subscribe';
}

However, what bugs me is that I have to write that same piece of code in my template file. I could however make an ajax call for that immediately as the page loads.

What is the best way of doing this?

A: 

Okay I decided to fix it using PHP. Now when you hit the page it calls for :

http://url/module/controller/check/id/$id/object/$object_name

and ajax'd it into my div. Then if its clicked it goes to and puts the return value in the html

http://url/module/controller/toggle/id/$id/object/$object_name

Class:

<?php


class User_SubscriptionController extends Zend_Controller_Action {


function init() {
    $contextSwitch  = $this->_helper->getHelper('ForceContext');
    $userSess       = new Zend_Session_Namespace('User');
    $this->user     = $userSess->model;

    $this->id           = $this->_getParam('id');
    $this->object_name  = $this->_getParam('object');

    if (empty($this->id) || empty($this->object_name)) {
        throw new exception('Id and Object name must be passed');
    }

}


public function checkAction() {

    $subscription = Eurocreme_Baseclass::load_by_fields(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription'), 1);

    if (is_object($subscription)) {
        echo 'Click To Un-Susbscribe';
    } else {
        echo 'Click To Subscribe';
    }
    exit;
}


public function toggleAction() {

    $subscription = Eurocreme_Baseclass::load_by_fields(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription'), 1);

    if (is_object($subscription)) {
        $subscription->delete();
    } else {
        $subscription = Eurocreme_Baseclass::create(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription', 'frequency' => 1));
    }

    $this->checkAction();
}

}

and the view code is:

<?php $this->headScript()->captureStart(); ?>
$('document').ready(function() { 

    $.get('/user/subscription/check/id/<?php echo $this->object->id; ?>/object/Movie', function(data) {
        $('#subscription_link').html(data);
    });

    $("#subscription_link").click(function(){
        $.get('/user/subscription/toggle/id/<?php echo $this->object->id; ?>/object/Movie', function(data) {
            $('#subscription_link').html(data);
        });
        return true;
    });


}); 
<?php $this->headScript()->captureEnd(); ?>
azz0r