开发者

Use jQuery to update database through Joomla MVC component

开发者 https://www.devze.com 2023-01-20 14:16 出处:网络
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

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 da开发者_如何学编程tabase 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消