views:

33

answers:

1

Hi

I am developing a new version of my Joomla component TTVideo. I'm trying setup a rating system using the jQuery stars plugin. I have the jQuery noconflict issue resolved, however I'm a bit confused as to how to send the vote securely to a helper class that updates the database with the value of the vote.

Usually this is done through an external script which is only every accessed by the ajax request. I would like to do this so it is incorporated within my component, and in such a fashion that the std Joomla variables are available to the helper class e.g. getDBO() and the database reference #__table_name.

Any comments on how to achieve this will be greatly appreciated. Thanks.

+1  A: 

That is pretty straight forward.

First, you need to create a controller with a specific task that handles your rating update. To make it secure, validate the token! The token will come with AJAX request.

Consider this example

function rate() {
    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    //  Get ID of item
    //  update rating, etc...
}

Second, create your AJAX request in the view, obviously triggered by some action. Make sure to send your request as POST because you are going to write data... You can either have your script in external document get values from html document (id, token, url, etc that are in hidden inputs) or you can generate javascript with PHP and include it in the head (like in example below).

<?php
//
$url = JRoute::_('index.php?option=my_component&controller=my_controller');
$token = JUtility::getToken();  //  <-  Session token
$id = 101;  //  <-  YOUR ID

//  This will add the request to the head of the document, instead of somewhere in the document
JFactory::getDocument()->addScriptDeclaration("
    .ajax({
        type: 'POST',
        url: $url,
        data: {
            '$token': '1', // <-- THIS IS IMPORTANT
            'task': 'rate',
            'id':  $id
        },
        success: youSuccessFunction
    }); 
");
?>

You might need to modify few things, but this is the idea behind AJAX in MVC.

NOTE: You can also call JRequest::checkToken('get') and this will check for the token in the url. This is useful for AJAX calls that read data.

Alex
Martin
Alex
format=raw **does not** call a view. view=raw would call a view, **format** is a std Joomla option to not return any other html apart from what the component returns. This is helpful when returning JSON as you don't want any other html/text in there at all else jQuery will not recognise it.
Martin
you are right, I did not express myself right. However, if your controller falls into `display()`, corresponding view will be called. and instead of `view.html.php` -> `view.raw.php` will be loaded. I do not see your logic with format usage, if you are returning JSON, it is logical to call `format=json`..., but everyone has their own practices and conventions. best of luck
Alex